将所有 xml 个节点的特定属性值导出到另一个文件

Export specific attribute value of all xml nodes to another file

我有一个 XML 结构如下的文档:

<root>
    <parent id="idvalue1" attr1="val1" attr2="val2" ...>
        <child attr3="val3" attr4="val4" ... />
        <child attr3="val5" attr4="val6" ... />
        ...
    </parent>
    <parent id="idvalue2" attr1="val7" attr2="val8" ... />
    ...
</root>

我想获取所有具有它的节点的 id 属性的所有值的列表。现在可以安全地假设只有第二级元素将具有 id 属性。

无论如何,执行此操作的最佳方法是什么?是 xmllintxpath 还是 xmlstarlet

I want to get a list of all the values of the id attributes of all the nodes which have it.

使用 XPath,您可以使用如下表达式:

//@id

我认为这很容易。如果你想要一些布局,你可以使用 XSLT:

<xsl:template match="/">
    <xsl:apply-templates select="//@*" />
</xsl:template>

<xsl:template match="@id">
    <xsl:text>Id is: </xsl:text>
    <xsl:value-of select="." />
    <xsl:text>&#xA;</xsl:text>
</xsl:text>

这将为您提供一个换行符分隔的列表,其中包含名称为 id.

的所有属性

您可以使用 xmlstarlet 输出列表:

    xmlstarlet sel -t -v "//@id" yourfile.xml

但是,这将仅输出 ID 值。

-t 选项 "creates" 一个像 Abel 的回答中建议的 XSLT。但输出只会是您使用 sel 命令 select 的内容。选项 -v 是在引号中打印 xpath 的值。 xpath 表达式中的双斜线调用所有节点。