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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20495885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:56:39  来源:igfitidea点击:

Bash script: Get XML elements into array using xmllint

xmlbashshell

提问by tzippy

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.

我想最终得到一个数组,其中包含<description>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>

回答by édouard Lopez

A Bashsolution could be

一个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[@]}

Disclaimer

免责声明

Consider that bashmay not be the right tool. XSLT/XPath could give you direct access to the content of the descriptionelement as describe in previous answer. For instance:

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

xmllint --xpath '//item/description/text()' /tmp/so.xml

Return every <description>content

返回所有<description>内容