如何使用xmllint从XML中获取属性值和元素值



有这样一个XML文件

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model-response-list xmlns="http://www.ca.com/spectrum/restful/schema/response" total-models="922" throttle="922" error="EndOfResults">
<model-responses>
<model mh="0x1058905">
<attribute id="0x1006e">prod-vpn-gw-v01.e-x.com</attribute>
</model>
<model mh="0x1058907">
<attribute id="0x1006e">prod-storage-san-z01-ssh.e-x.com</attribute>
</model>
<model mh="0x1058900">
<attribute id="0x1006e">test-vpn-gw-v01</attribute>
</model>
</model-responses>
</model-response-list>

我需要打印一个列表:

0x1058905 prod-vpn-gw-v01.e-x.com
0x1058907 prod-storage-san-z01-ssh.e-x.com
0x1058900 test-vpn-gw-v01

I tried with:

xmllint --xpath "//*[local-name()='model']/*[local-name()='attribute']/text()" devices.xml

,但它只是名称,真的不知道如何使用它与一个和在它得到也0x…mh价值。

有人能帮忙吗?谢谢你。

另一种选择是使用xmlstarlet匹配model元素,然后使用concat()输出所需的值…

xmlstarlet sel -t -m "//_:model" -v "concat(@mh,' ',_:attribute)" -n devices.xml

输出……

0x1058905 prod-vpn-gw-v01.e-x.com
0x1058907 prod-storage-san-z01-ssh.e-x.com
0x1058900 test-vpn-gw-v01

注意:我使用的是1.6.1版本的xmlstarlet。并非所有版本都支持"_"用于名称空间前缀。(在1.5.0+版本中支持)

请参阅http://xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html#idm47077139652416了解更多关于"自我"的信息。xmlstarlet命令。

xmllint不是理想的工具(它只支持xpath 1.0),但如果您必须使用它,请尝试以下操作;它应该能让你足够接近:

xmllint --xpath ".//*[local-name()='model']/@mh | .//*[local-name()='model']//*/text()"  devices.xml

输出:

mh="0x1058905"
prod-vpn-gw-v01.e-x.com
mh="0x1058907"
prod-storage-san-z01-ssh.e-x.com
mh="0x1058900"
test-vpn-gw-v01

最新更新