我有一个需要从 shell 解析的 XML 文件。它看起来有点像这样:
<?xml version="1.0" encoding="UTF-8"?>
<things>
<thing>
<foo>123</foo>
<bar>false</bar>
</thing>
<thing>
<bar>true</bar>
<foo>abc</foo>
</thing>
</things>
Run Code Online (Sandbox Code Playgroud)
请注意,things的子节点的顺序是任意的。在我的真实数据中,每个thing.
现在, 的值foo是唯一的。我需要的子节点的值bar了thing其子foo的价值,比如说,abc。我尝试使用 XPath 查询,xmllint但没有运气。我找不到火柴;或者,如果我只是用更一般的查询进行测试,我会得到整个树。
$ xmllint --pattern //thing[foo='abc']/bar test.xml
xmllint: No match.
$ xmllint --pattern //thing/bar test.xml
(the whole tree)
Run Code Online (Sandbox Code Playgroud)
我希望只是得到true。
我究竟做错了什么?我无法访问--xpath其他问题提到的标志,所以如果这是答案,那么我就不走运了。
试试这个命令:
xmllint --xpath '//thing[foo="abc"]/bar/text()' test.xml
Run Code Online (Sandbox Code Playgroud)
另一个命令:
echo 'cat //thing[foo="abc"]/bar/text()' | xmllint --shell test.xml
Run Code Online (Sandbox Code Playgroud)
也试试xmlstarlet:
xmlstarlet sel -t -m '//thing[foo="abc"]/bar' -v 'text()' test.xml
Run Code Online (Sandbox Code Playgroud)