Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Parse XML to comma separated list

Tags:

bash

xml

csv

xpath

How do I return a comma-separated list of the ids, please?

<nodes>
 <node>
   <id>1</id>
   <name>idbread</name>
 </node>
 <node>
   <id>2</id>
   <name>idbutter</name>
 </node>
</nodes> 

expected output

1,2

I attempted to use XPath, but concat returns only the first value.

xpath node.xml "//nodes/node/id/text()" 2>/dev/null

returns

12

like image 714
mr i.o Avatar asked Nov 25 '25 23:11

mr i.o


1 Answers

You can use xmlstarlet for this:

xmlstarlet sel -t -v "/nodes/node[1]/id" -m "/nodes/node[position()>1]" -v "concat(',',id)" input.xml

This outputs the value of the first node/id node and then outputs the following node/ids separated by a comma. The output is as desired.

  • The sel option chooses the Select/Query mode of xmlstarlet
  • The -t indicates the start of an "XSLT template"
  • The first -v option outputs the value of the XPath expression
  • The -m option creates a for-each over the XPath expression
  • The second -v option outputs the value of the XPath expression relative to the context value of the for-each
like image 79
zx485 Avatar answered Nov 27 '25 13:11

zx485