Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Node value from a XML using xmllint

Tags:

unix

xmllint

I have a xml called Det.xml like this :

<?xml version="1.0" encoding="UTF-8"?>
    <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
        <S:Body>
            <ns4:grtHgetRed xmlns:ns2="http://object" xmlns:ns3="http://object" xmlns:ns4="http://object">
                <RequestId>lol</RequestId>
                <MessageDateTime>54.009</MessageDateTime>
                <SenderId>UH</SenderId>
                <ReceiverId>GER</ReceiverId>
                <TrackingNumber>45</TrackingNumber>
                <ServerName>trewds</ServerName>
                <ResponseType>success</ResponseType>
                <StatusInfo>
                <Status>success</Status>
                <SystemMessage>Hagert</SystemMessage>
                <UserMessage>Hgert</UserMessage>
                <Origination>htref</Origination>
                </StatusInfo>
            </ns4:grtHgetRed>
        </S:Body>
    </S:Envelope>

I am trying to get the ResponseType node value success from it using xmllint in Unix shell script and so i tried the following :

echo "cat //*[local-name()='S:Envelope'/*[local-name()='S:Body']/*[local-name()='ns4:grtHgetRed']/*[local-name()='ResponseType']" | xmllint --shell Det
.xml | sed '/^\/ >/d' | sed 's/<[^>]*.//g'

But it's not working . Also i don't have xpath in my unix environment . Can any one tell me what am i doing wrong here ?

like image 330
The Dark Knight Avatar asked Oct 03 '22 21:10

The Dark Knight


2 Answers

The local-name() is just the bit after the colon, so instead of e.g. local-name()='S:Envelope' try just local-name()='Envelope'.

/*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='grtHgetRed']/*[local-name()='ResponseType']

Or you may want to consider an alternative tool such as xmlstarlet which has better support for this kind of thing.

like image 138
Ian Roberts Avatar answered Oct 13 '22 11:10

Ian Roberts


If there is only ever a single ResponseType element in the XML, use the following to simplify things:

echo 'cat //ResponseType/text()' | xmllint --shell det.xml

The // is XPath syntax for "find this element anywhere in the document".

The text() function returns the contents of the element, meaning you do not need the further massage the result with sed et. al.

This worked for me on both a Solaris and Linux box for which xmllint does not have the --xpath option available.

like image 21
jpwilksch Avatar answered Oct 13 '22 12:10

jpwilksch