0

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.

F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137
Yankee
  • 17
  • 6
  • 1
    That question isn't *quite* a duplicate... It's about extracting an attribute value, not the body of a tag. The answer is going to be very similar, though - just a bit different XPath expression. – Shawn Mar 18 '21 at 07:02
  • Yes @Shawn, I went through a lot of questions in which the value was present in the tag itself. I tried modifying those answers but couldn't reach a solution. Thanks for reopening. – Yankee Mar 18 '21 at 08:52

1 Answers1

5

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)
Luuk
  • 12,245
  • 5
  • 22
  • 33
  • 2
    The awk one (and it's common to all awks, not gawk-specific) would be more robust as `awk -F'[<>]' '$2=="ver"{ print $3 }'`. That would not fail if `` just happened to exist in some other string in the input. – Ed Morton Mar 18 '21 at 16:35
  • 2
    Thanks Ed, I will always leave some improvement for you – Luuk Mar 18 '21 at 17:24
  • Using [tag:xidel]: `ver=$(xidel -s test.xml -e '//ver')` or `eval "$(xidel -s test.xml -e 'ver:=//ver' --output-format=bash)"` – Reino Mar 23 '21 at 00:01