【问题标题】:Get value of an attribute from xml for multiple occurrences using xmllint使用 xmllint 从 xml 中获取多次出现的属性值
【发布时间】:2015-11-02 11:53:41
【问题描述】:

我想获取名称为 3 的 abc 的 conn 值,即 conn3

<abc name="1">
    <properties conn="conn1"/>
</abc>
<abc name="2">
    <properties conn="conn2"/>
</abc>
<abc name="3">
    <properties conn="conn3"/>
</abc>

目前我正在做

echo 'cat //abc/properties/@conn' | xmllint --shell "test.xml"

但它返回 conn1,conn2,conn3

我正在尝试

echo 'cat //abc[@name='1']/properties/@conn' | xmllint --shell "test.xml"

但它没有返回任何东西

您能否建议我在哪里做错了。 Note:Xpath 不支持

【问题讨论】:

  • 鉴于该 XML(并将其包装在 &lt;root&gt; 元素中以使其有效),您的第二个命令对我有用。我猜你有什么不同的东西?
  • 也适合我。虽然如果您没有 --xpath 选项,我想知道您的 xmllint 是否旧且不支持您正在使用的特定查询...
  • 打印“/ > / >”到控制台
  • 预期的输出究竟是什么?兄弟姐妹相关:stackoverflow.com/questions/26823736/…

标签: xml linux shell unix xmllint


【解决方案1】:

最后的问题是命令下面的单引号(')对我有用。不知道是什么原因,一试就知道了:)

如果您知道背后的原因,请发表评论。

echo 'cat //abc[@name="1"]/properties/@conn' | xmllint --shell "test.xml"

注意:上面提到的 XML 只是我想要运行的示例实际 XML 是复杂的结构。

【讨论】:

    【解决方案2】:

    正常使用xmllint,不用管道:

    $ xmllint --xpath 'string(//abc[@name='1']/properties/@conn)' xml_file
    conn1
    

    参见string() 用于获取属性的值,如Getting attribute using XPath 中所述。

    【讨论】:

    • 嗨,--xpath 不支持 :(
    • 您的xmllint --version 会返回什么?我的xmllint: using libxml version 20901.
    • xmllint:使用 libxml 版本 20706 我正在使用 linux box xmllint --xpath 未知选项 --xpath 用法:xmllint [options] XMLfiles .
    猜你喜欢
    • 2018-07-13
    • 2023-02-20
    • 2021-05-27
    • 2012-02-15
    • 1970-01-01
    • 2016-11-05
    • 2021-02-01
    • 2013-11-15
    • 1970-01-01
    相关资源
    最近更新 更多