Search code examples
xmlxpathxmllint

How to get attribute value and element value from XML with xmllint


Have such a XML file.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model-response-list xmlns="http://www.ca.com/spectrum/restful/schema/response" total-models="922" throttle="922" error="EndOfResults">
    <model-responses>
        <model mh="0x1058905">
            <attribute id="0x1006e">prod-vpn-gw-v01.e-x.com</attribute>
        </model>
        <model mh="0x1058907">
            <attribute id="0x1006e">prod-storage-san-z01-ssh.e-x.com</attribute>
        </model>
        <model mh="0x1058900">
            <attribute id="0x1006e">test-vpn-gw-v01</attribute>
        </model>
    </model-responses>
</model-response-list>

I need to print a list:

0x1058905 prod-vpn-gw-v01.e-x.com
0x1058907 prod-storage-san-z01-ssh.e-x.com
0x1058900 test-vpn-gw-v01

I tried with:

xmllint --xpath "//*[local-name()='model']/*[local-name()='attribute']/text()" devices.xml

but its only for the name, really no idea how to use it with an and in it to get also the 0x... mh value.

Can some one help? Thank You.


Solution

  • Another option would be to use xmlstarlet to match the model elements and then use concat() to output the desired values...

    xmlstarlet sel -t -m "//_:model" -v "concat(@mh,' ',_:attribute)" -n devices.xml
    

    outputs...

    0x1058905 prod-vpn-gw-v01.e-x.com
    0x1058907 prod-storage-san-z01-ssh.e-x.com
    0x1058900 test-vpn-gw-v01
    

    Note: I'm using version 1.6.1 of xmlstarlet. Not all versions support "_" for a namespace prefix. (Supported in versions 1.5.0+)

    See http://xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html#idm47077139652416 for more info on the "sel" command of xmlstarlet.