bash脚本:使用xmllint获取XML元素到数组 [英] Bash script: Get XML elements into array using xmllint

查看:2444
本文介绍了bash脚本:使用xmllint获取XML元素到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个跟进问题<一href=\"http://stackoverflow.com/questions/20489279/get-valid-url-from-string-using-bash-script/20490304\">this帖子。

我想一个数组来结束,包含所有&LT;描述方式&gt; 的XML元素

 数组[0] =&LT;![CDATA [A的冠军......&LT; BR /&GT;]]&gt;中
阵列[1] =&LT;![CDATA [A的冠军......&LT; BR /&GT;]]&gt;中

...

  file.xml:&LT;项目&GT;
    &LT;描述&GT;&LT;![CDATA [A的网址&LT称号; BR /&GT;&LT; BR /&GT;    http://www.foobar.com/foo/bar
    &LT; BR />http://bar.com/foo
    &LT; BR />http://myurl.com/foo
    &LT; BR />http://desiredURL.com/files/ddd
    &LT; BR />http://asdasd.com/onefile/g.html
    &LT; BR />http://second.com/link
    &LT; BR /&GT;]]&GT;&LT; /描述&GT;
&LT; /项目&GT;
    &LT; /项目&GT;
&LT;描述&GT; ...&LT; /描述&GT;
    &LT;项目&GT;


解决方案

A 解决方案可能是

 让itemsCount = $(xmllint --xpath'计数(//项目/说明)/tmp/so.xml)
声明-a描述=()为((i = 1; I&LT; = $ itemsCount;我++));做
    说明[$ i] =$(xmllint --xpath'//项目['$ I'] /说明'/tmp/so.xml)
DONE回声$ {描述[@]}

免责声明

考虑到庆典未必是合适的工具。 XSLT / XPath的可以给你的说明元素的内容直接获得在previous答案形容。例如:

  xmllint --xpath'//商品/描述/文()'/tmp/so.xml

返回每个&LT;描述&GT; 内容

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>

解决方案

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

这篇关于bash脚本:使用xmllint获取XML元素到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆