Bash script: Get XML elements into array using xmllint
15,232
A Bash
solution could be
let itemsCount=$(xmllint --xpath 'count(//item/description)' /tmp/so.xml)
declare -a description=( )
for (( i=1; i <= $itemsCount; i++ )); do
description[$i]="$(xmllint --xpath '//item['$i']/description' /tmp/so.xml)"
done
echo ${description[@]}
Disclaimer
Consider that bash
may not be the right tool. XSLT/XPath could give you direct access to the content of the description
element as describe in previous answer. For instance:
xmllint --xpath '//item/description/text()' /tmp/so.xml
Return every <description>
content
Author by
tzippy
Updated on June 04, 2022Comments
-
tzippy about 2 years
This is a follow up question to this post.
I want to end up with an array, containing all the
<description>
elements of the xml.array[0] = "<![CDATA[A title for .... <br />]]>" array[1] = "<![CDATA[A title for .... <br />]]>"
...
file.xml: <item> <description><![CDATA[A title for the URLs<br /><br /> http://www.foobar.com/foo/bar <br />http://bar.com/foo <br />http://myurl.com/foo <br />http://desiredURL.com/files/ddd <br />http://asdasd.com/onefile/g.html <br />http://second.com/link <br />]]></description> </item> </item> <description> ...</description> <item>
-
Édouard Lopez over 10 yearswhy do you want to store them in an array ?
-
tzippy over 10 yearsI want to extract values from each array object. What better solution thatn an array would you suggest? What would be an Xpath expression for that?
-
-
tzippy over 10 yearsThank you! The thing is that, what you described in your disclaimer, returns all the content of the description elements in one string. That's not too useful for further processing.
-
Édouard Lopez over 10 yearscode before disclaimer should do what you ask. Disclaimer is here to only if you don't care/need the element
description
that serve as source -
JulianM about 8 yearsI think in the bash solution it should be "smallerThanOrEqualTo" <= for (( i=1; i <= $itemsCount; i++ )); do