Search code examples
xmlshellawkgrepxmllint

How to extract values from an xml file using shell script?


I have this xml file.

<body>
<part1>
   <para1>abc</para1>
   <para2>def</para2>
   <ver>1234</ver>
</part1>    
</body>

I need to store the value given by ver i.e. 1234 in a variable.


Solution

  • Different options:

    1. using xmlstarlet:
    ver=$(xmlstarlet sel -t -m //ver -v . test.xml)
    
    1. using xmllint (see also Native shell command set to extract node value from XML:
    ver=$(xmllint --xpath "//ver/text()" test.xml)
    
    1. Using gawk:
    ver=$(gawk -F "[><]" '/<ver>/{ print $3 }' test.xml)