Search code examples
xmlxpathxmllint

Getting multiple attribute values from XML via xpath


I'm trying to retrieve multiple attribute values (foo and bar) with one single xpath query.

This is my XML content (test.xml):

<root>
    <level1>
        <child foo="bar" bar="foo" />
    </level1>
</root>

Current best solution based on:

xmllint test.xml --xpath '//root/level1/child/@*[name()="foo" or name()="bar"]'
xpath -q -e '//root/level1/child/@*[name()="foo" or name()="bar"]' test.xml

..which both return:

 foo="bar"
 bar="foo"

However I would like to have an output similar this (attribute names and =" removed):

bar
foo

Wrapping the query with string() sadly doesn't work.

Is it actually possible to get multiple attribute values at once, or am I trying something impossible?

I'm aware that I could pipe the output through cut or awk but that isn't possible in the actual environment.


Solution

  • Found a solution!

    There is a function available called concat which allows exactly the functionality I was looking for:

    xpath -q -e 'concat(string(//root/level1/child/@foo), "\n", string(//root/level1/child/@bar))' test.xml
    

    This allows me to query both attribute values (using string) in one query.