如何使用Xsl向Xml文件中的每个节点添加特定属性?

时间:2010-06-30 00:41:39

标签: xml xslt

我有一点看起来像这样的Xml:

<books>
  <book id="1">
    <name>My book</name>
    <author>My author</author>
  </book>
  <book id="2">
    <name>My other book</name>
    <author>My other author</author>
  </book>
</books>

我希望看起来像:

<books>
  <book id="1">
    <name id="1">My book</name>
    <author id="1">My author</author>
  </book>
  <book id="2">
    <name id="2">My other book</name>
    <author id="2">My other author</author>
  </book>
</books>

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:4)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <!--Standard identity template that copies all content -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--special template for elements who's parent has an @id -->
    <xsl:template match="*[../@id]">
        <xsl:copy>
            <xsl:copy-of select="../@id" />
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>