Search code examples
bashxmllint

Look for more then one value using xmllint


I need to retrieve more then one value from several XML-blocks inside a XML-file. How can I use xmllint to do this?

I noticed this solution (xml_grep get attribute from element) and tried to extend it. Unfortunately without any luck so far.

xmllint --xpath 'string(//identity/@name @placeofbirth @photo)' file.xml

Example XML file:

 <eid>
   <identity>
      <name>Menten</name>
      <firstname>Kasper</firstname>
      <middlenames>Marie J</middlenames>
      <nationality>Belg</nationality>
      <placeofbirth>Sint-Truiden</placeofbirth>
      <photo>base64-string</photo>
    </identity>
    <identity>
      <name>Herbal</name>
      <firstname>Jane</firstname>
      <middlenames>Helena</middlenames>
      <nationality>Frans</nationality>
      <placeofbirth>Paris</placeofbirth>
      <photo>notavailable</photo>
    </identity>
 </eid>

Output wanted

Kasper, Sint-Truiden, base64-string
Jane, Paris, notavailable

Solution

  • One way to do that is

    # Read xml into variable
    xmlStr=$(cat test.xml)
    # Count identity nodes
    nodeCount=$(echo "$xmlStr" | xmllint --xpath "count(//identity)" -)
    # Iterate the nodeset by index
    for i in $(seq 1 $nodeCount);do
       echo "$xmlStr" | xmllint --xpath "concat((//identity)[$i]/name,', ',(//identity)[$i]/placeofbirth, ', ', (//identity)[$i]/photo)" - ; echo
    done
    

    Result:

    Menten, Sint-Truiden, base64-string
    Herbal, Paris, notavailable