xml - Bash 脚本 : Get XML elements into array using xmllint

标签 xml bash shell

这是对 this post 的后续问题.

我想以一个数组结束,其中包含所有 <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>

最佳答案

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

免责声明

考虑 bash可能不是正确的工具。 XSLT/XPath 可以让您直接访问 description 的内容上一个答案中描述的元素。例如:

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

返回每 <description>内容

关于xml - Bash 脚本 : Get XML elements into array using xmllint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20495885/

相关文章:

不合格属性名称的 XML 默认命名空间?

linux - 将变量传递到 BASH 函数时出现“未找到命令”,我是否引用错误?

linux - 如何检查 sed 命令是否替换了一些字符串?

bash - 实时修改shell stdout

.net - .net 中是否有读取 XML 注释文档文件的 API

android - 如何使用 DOM 从这个 XML 中解析 <img src ="value"?

xml - XSD:允许任何未知元素以任何顺序

regex - fgrep 匹配文字 "*"

linux - 从脚本调用时,Bash find 无法返回所有匹配的文件

shell - AWK 使用空格和正斜杠或逗号作为分隔符