Parsing xml to and replacing specific tags shell script

给你一囗甜甜゛ 提交于 2019-12-03 09:08:26

Update value with xmllint in file.xml:

xmllint --shell file.xml << EOF
cd /studentFile/student[studentName='CLASSA']/studentActions/studentAction[studentType='Juniour']/studentStatus
set failed
save
EOF

or without here document:

echo -e "cd /studentFile/student[studentName='CLASSA']/studentActions/studentAction[studentType='Juniour']/studentStatus\nset failed\nsave" | xmllint --shell file.xml

Update: With bash and XML in a variable:

xml=$(xmllint --shell <(echo "$xml") << EOF
cd /studentFile/student[studentName='CLASSA']/studentActions/studentAction[studentType='Juniour']/studentStatus
set failed
save -
EOF
)

or without here document:

xml=$(echo -e "cd /studentFile/student[studentName='CLASSA']/studentActions/studentAction[studentType='Juniour']/studentStatus\nset failed\nsave -" | xmllint --shell <(echo "$xml"))

xlmlint, as the name implies, is for parsing and validating XML, not editing it. If you can install xmlstarlet on your cluster, you can do the following:

xmlstarlet ed --update "/studentFile/student[studentName='CLASSA']/studentActions/studentAction[studentType='Juniour']/studentStatus" --value "Failed" *file*

In case if xmlstarlet (a command line toolkit to query/edit/check/transform XML documents) is accessible:

xmlstarlet ed -u "//studentAction/studentStatus[preceding-sibling::studentType[1][text() = 'Juniour'] \
           and ancestor::student/studentName[text() = 'CLASSA']]" -v failed students.xml

The above will output the initial XML document with needed replacement


The command details:

ed -u - edit/update mode

//studentAction/studentStatus - xpath expression to select studentStatus element which has:

  • preceding-sibling::studentType[1][text() = 'Juniour'] - preceding sibling element studentType with value Juniour
  • ancestor::student/studentName[text() = 'CLASSA'] - nearest element studentName with value CLASSA
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!