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
0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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 ;-).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.