Bash脚本:使用xmllint将XML元素放入数组中

tzi*_*ppy 3 xml bash shell

这是一个后续的问题 这篇文章.

我想最终得到一个数组,包含<description>xml的所有元素.

array[0] = "<![CDATA[A title for .... <br />]]>"
array[1] = "<![CDATA[A title for .... <br />]]>"
Run Code Online (Sandbox Code Playgroud)

...

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>
Run Code Online (Sandbox Code Playgroud)

Édo*_*pez 10

一个Bash解决办法是

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[@]}
Run Code Online (Sandbox Code Playgroud)

放弃

考虑一下bash可能不是正确的工具.XSLT/XPath可以让您直接访问description元素的内容,如前面的答案中所述.例如:

xmllint --xpath '//item/description/text()' /tmp/so.xml
Run Code Online (Sandbox Code Playgroud)

返回每个<description>内容