0

Is there a way that I can retrieve the value of an element (or the tag) in XML through a bash script?

For example, if I had the below XML, I'd like to retrieve the element , so that when I run the command, it simply returns "tag1" rather than any content within any of the other tags. I know I can use xmllint if I wanted to retrieve the valueTag3 content for example, but that is not what I'd like to do.

<tag1>
    <tag2>
        <tag3>valueTag3</tag3>
    </tag2>
</tag1>

If the above is possible (whether using xmllint or not), is there a way that I can specify that I'd like to return a child tag of its parent tag? For example, what would be the command if I wanted to return "tag2" (which is a child of tag1 above)?

1
  • tag2 doesn't follow tag1, tag2 is tag1's child. Commented Jul 31, 2019 at 8:59

1 Answer 1

1

See XPath syntax:

xmllint -xpath 'name(/tag1/tag2/*)' xmlsource
Sign up to request clarification or add additional context in comments.

3 Comments

I've run the above command and it returns "valueTag3". As mentioned above, I'd like to return the tag itself (tag3 for example) rather than the value within it.
Oh, then you need to use name() function of XPath like this: xmllint -xpath 'name(/tag1/tag2/*) (Fixed above)
Perfect, thank you! I also found a potential solution using xmlStarlet which returns the structure of the xml file: xml sel -T -t -m '//*' \ -m 'ancestor-or-self::*' -v 'name()' -i 'not(position()=last())' -o . -b -b -n \ source.xml which could be handy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.