Search code examples
xmlbashxpathxmlstarlet

Extract specific values from XML configuration


Input XML looks like several blocks of:

<Parties>
  <Party compid="CUST1" side="1">
                <Connections>
                    <SocketConnection listenport="9029" />
                </Connections>
   </Party>
</Parties>

My goal is to extract to each customer his specific params like: compid;listenport

By now I can get all customers using

xmlstarlet fo -D config.xml | xmlstarlet select -T -t -m '//Parties/Party' -v '@compid' -nl

Next step would be a loop for each customer to get his listenport, but

xmlstarlet fo -D config.xml | xmlstarlet select -T -t -m '//Parties/Party[@compid="CUST1"]' -v 'Connections/SocketConnection/@listenport'

or any other try returns nothing. Am I missing something at filtering using [@value=string]?

Thanks in advance!


Solution

  • With your example and xmlstarlet:

    xmlstarlet select --text --template --match '//Parties/Party' --value-of \
      'concat(@compid,";",Connections/SocketConnection/@listenport)' -n config.xml
    

    Output:

    CUST1;9029
    

    See: xmlstarlet select --help