使用 xmllint 获取多个值

Bil*_*l T 8 xml xpath xmllint

我想使用 xmllint 中的 xpath 来获取主机名和序列号。

这是 XML

<hosts>
 <host name="blah001" serial="ABC001">
  <moreinfo />
 </host>
 <host name="blah002" serial="ABC002">
  <moreinfo />
 </host>
 ..
</hosts>
Run Code Online (Sandbox Code Playgroud)

我可以使用主机名 blah* 获取所有连续剧:

/ > cat //hosts/host[starts-with(@name,"blah")]/@serial
 -------
 serial="ABC001"
 -------
 serial="ABC002"
Run Code Online (Sandbox Code Playgroud)

但我也想看看哪个主机名有那个序列号。那可能吗?

Mat*_*ler 6

也许简单地选择host元素的所有属性就足够了?

$ xmllint example.xml --xpath "//hosts/host[starts-with(@name,"blah")]/@*" > out.txt
$ cat out.txt
  name="blah001" serial="ABC001" name="blah002" serial="ABC002"
Run Code Online (Sandbox Code Playgroud)

如果这还不够 - 如果输出应该以某种方式构建,我建议您编写一个简单的 XSLT 转换或使用 XQuery。

编辑

所以我会遵循你的建议并使用 xslt 或 xquery

很好,如果您决定使用 XSLT,您需要的样式表将类似于:

XSLT 样式表 (1.0)

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text" encoding="UTF-8" />

    <xsl:template match="host[starts-with(@name,'blah')]">
        <xsl:value-of select="concat('HOST: ',@name, ' SERIAL: ', @serial)"/>
    </xsl:template>
</xsl:transform>
Run Code Online (Sandbox Code Playgroud)

输出

 HOST: blah001 SERIAL: ABC001
 HOST: blah002 SERIAL: ABC002
Run Code Online (Sandbox Code Playgroud)


小智 6

这可以在 xmllint 中使用以下 XPath 表达式完成。假设您的 XML 名为 hosts.xml。

xmllint hosts.xml --xpath '//host[starts-with(@name,"blah")]/@name | //host[starts-with(@name,"blah")]/@serial' | xargs -n2
Run Code Online (Sandbox Code Playgroud)

这是因为 | XPath 表达式中的运算符可以支持多个路径。