【问题标题】:How to get mh value and name from XML with xmllint如何使用 xmllint 从 XML 中获取 mh 值和名称
【发布时间】:2021-05-27 23:43:17
【问题描述】:

有这样一个 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 测试-vpn-gw-v01

我试过了:

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

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

有人可以帮忙吗? 谢谢。

【问题讨论】:

    标签: xml xmllint


    【解决方案1】:

    另一种选择是使用 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+版本支持)

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

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

      • 嗯,我可以用别的东西,有什么建议吗? Python?还是别的什么?
      • @Bomber 是的,用 python 很容易。
      猜你喜欢
      • 1970-01-01
      • 2015-11-02
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2017-09-27
      • 1970-01-01
      • 2019-01-24
      相关资源
      最近更新 更多