繁体   English   中英

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

[英]How to get attribute value and element value from XML with xmllint

有这样一个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

我试过:

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

但它只是为了名称,真的不知道如何将它与 an 一起使用以获得 0x... mh 值。

有人可以帮忙吗? 谢谢你。

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

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

Output:

 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

另一种选择是使用xmlstarlet来匹配model元素,然后使用 concat() 到 output 所需的值...

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

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

有关 xmlstarlet 的“sel”命令的更多信息,请参阅http: //xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html#idm47077139652416。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM