如何使用XSLT重命名属性?

时间:2010-04-20 23:40:37

标签: xml xslt

我有一个像这样的xml:

<person name="foo" gender = "male" />

我想将其转换为

<person id="foo" gender="male" />

有没有办法使用XSLT做到这一点?

  • 我会有很多子节点

  • 我会在这个人身上拥有更多属性。

2 个答案:

答案 0 :(得分:15)

这非常简单:使用身份转换并创建一个转换name属性的模板:

<xsl:template match="node()|@*">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="@name">
   <xsl:attribute name="id">
      <xsl:value-of select="."/>
   </xsl:attribute>
</xsl:template>

除了name属性之外,这将完全保留文档中的所有内容。如果您只想更改name元素的person属性,请在模板的match属性中添加更严格的XPath,例如person/@name

答案 1 :(得分:-1)

这应该这样做,不完全确定{name()}但你可以用“person”替换它

> <xsl:template match="person">
>       <xsl:element name="{name()}">
>         <xsl:attribute name="id">
>           <xsl:value-of select="@name"/>
>         </xsl:attribute>
>         <xsl:attribute name="gender">
>           <xsl:value-of select="@gender"/>
>         </xsl:attribute>
>       </xsl:element>
>     </xsl:template>