Search code examples
xmlbashxmllint

Retrieve Element Tag Value XML Using Bash


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)?


Solution

  • See XPath syntax:

    xmllint -xpath 'name(/tag1/tag2/*)' xmlsource