0

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
NetMonk
  • 55
  • 6

1 Answers1

2

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
LMC
  • 10,453
  • 2
  • 27
  • 52
  • Thanks a lot. Your solutions works like a charm. I only need to look for a way to make it faster. It's a file of 62MB ;-). – NetMonk Apr 25 '19 at 09:21