1

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.

2
  • 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
    CommentedMar 18, 2021 at 7: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
    CommentedMar 18, 2021 at 8:52

1 Answer 1

7

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) 
3
  • 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 <ver> just happened to exist in some other string in the input.
    – Ed Morton
    CommentedMar 18, 2021 at 16:35
  • 2
    Thanks Ed, I will always leave some improvement for you 😁😉
    – Luuk
    CommentedMar 18, 2021 at 17:24
  • Using xidel: ver=$(xidel -s test.xml -e '//ver') or eval "$(xidel -s test.xml -e 'ver:=//ver' --output-format=bash)"
    – Reino
    CommentedMar 23, 2021 at 0:01

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.