【问题标题】:How do you use the --pattern option of xmllint?如何使用 xmllint 的 --pattern 选项?
【发布时间】:2011-01-14 12:58:54
【问题描述】:

我正在尝试了解 libxml 如何实现 XPath 支持,因此使用 xmllint 进行测试对我来说是有意义的。然而,显而易见的选项 --pattern 有点晦涩难懂,我最终使用了类似以下的选项:

test.xml: <foo><bar/><bar/></foo>

> xmllint --shell test.xml
/  > dir /foo
ELEMENT foo
/  > dir /foo/*
ELEMENT bar
ELEMENT bar

这似乎有效,这很好,但我仍然很好奇。 xmllint 的 --pattern 选项有什么用,它是如何工作的?

提供一个完整的例子。 =)

【问题讨论】:

    标签: xpath libxml2


    【解决方案1】:

    来自 xmllint(1) 手册页:

       --pattern PATTERNVALUE
              Used to exercise the pattern recognition engine, which can be
              used with the reader interface to the parser. It allows to
              select some nodes in the document based on an XPath (subset)
              expression. Used for debugging.
    

    它只理解 XPath 的一个子集,其目的是帮助调试。完全理解 XPath 的库是 libxslt(3) 及其命令行工具 xsltproc(1)。

    libxml 中的“模式”模块“允许编译和测试树中节点或基于解析器状态的模式表达式”,其文档位于:http://xmlsoft.org/html/libxml-pattern.html

    阿里。

    【讨论】:

    • 我也可以阅读 xmllint 手册页!但是,它并没有告诉我我想知道什么。使用 xmllint --pattern 似乎总是吐出整个文档,这就是我首先问这个问题的原因。就像我说的,“提供一个完整的例子”。
    【解决方案2】:

    看似未记录的选项 --xpath 似乎更有用。

    % cat data.xml
    <project>
      <name>
        bob
      </name>
      <version>
        1.1.1
      </version>
    </project>
    % xmllint --xpath '/project/version/text()' data.xml | xargs -i echo -n "{}"
    1.1.1
    % xmllint --xpath '/project/name/text()' data.xml | xargs -i echo -n "{}"
    bob
    

    【讨论】:

    • 嗯,自从我上次更新库以来,似乎添加了该选项。我下次更新时会检查一下。谢谢!
    【解决方案3】:

    提示是“可以与解析器的阅读器接口一起使用”:xmllint 仅在传递 --stream 选项时使用阅读器接口:

    $ xmllint --stream --pattern /foo/bar test.xml
    Node /foo/bar[1] matches pattern /foo/bar
    Node /foo/bar matches pattern /foo/bar
    

    【讨论】:

      【解决方案4】:

      如果您只是想要多个 xml 节点的文本值,那么您可以使用类似的东西(如果 --xpath 在您的 xmllint 版本上不可用):

      ./foo.xml:
      
      <hello>
         <world>its alive!!</world>
         <world>and works!!</world>
      </hello>
      
      $ xmllint --stream --pattern /hello/world --debug ./foo.xml | grep -A 1 "matches pattern" | grep "#text" | sed 's/.* [0-9] //'
      its alive!!
      and works!!
      

      【讨论】:

        猜你喜欢
        • 2012-08-12
        • 2019-02-10
        • 1970-01-01
        • 2015-08-19
        • 1970-01-01
        • 2021-07-12
        • 2021-11-25
        • 2020-10-21
        • 2015-05-18
        相关资源
        最近更新 更多