6

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>
2
  • why do you want to store them in an array ? Commented Dec 10, 2013 at 13:44
  • I 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? Commented Dec 10, 2013 at 13:54

1 Answer 1

17

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank 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.
code 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
I think in the bash solution it should be "smallerThanOrEqualTo" <= for (( i=1; i <= $itemsCount; i++ )); do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.