The Dark Knight
The Dark Knight

Reputation: 5585

Get Node value from a XML using 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 ?

Upvotes: 5

Views: 11645

Answers (3)

jpwilksch
jpwilksch

Reputation: 41

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.

Upvotes: 1

Ian Roberts
Ian Roberts

Reputation: 122364

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.

Upvotes: 3

TheLostMind
TheLostMind

Reputation: 36304

I don't know what you are doing wrong... If using XMLlint is not mandatory, you can use JDom, works like a charm for requirements like yours... Just a suggestion...

Upvotes: 0

Related Questions