<xsl:attribute> 元素是在XSLT中用于为生成的元素添加属性的元素。它允许你在XSLT模板中动态地为输出的XML元素设置属性值。

以下是一个简单的示例,演示了如何使用 <xsl:attribute> 元素:

假设有一个XML文档如下:
<book>
  <title>Introduction to XSLT</title>
  <author>John Doe</author>
</book>

然后有一个XSLT样式表,使用 <xsl:attribute> 来动态添加一个额外的属性:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <!-- Identity template to copy everything as is -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- Template for adding an attribute to the 'book' element -->
  <xsl:template match="book">
    <xsl:copy>
      <!-- Use xsl:attribute to add an 'edition' attribute with the value '1' -->
      <xsl:attribute name="edition">1</xsl:attribute>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

在这个例子中,XSLT样式表有两个模板:

1. Identity Template: 用于复制文档中的所有节点和属性。

2. Template for 'book' Element: 用于匹配 book 元素,然后使用 <xsl:attribute> 添加一个名为 edition 的属性,并设置其值为 1。接着,使用 <xsl:apply-templates> 处理其他节点和属性。

当对上述XML文档应用此XSLT样式表时,输出将是:
<book edition="1">
  <title>Introduction to XSLT</title>
  <author>John Doe</author>
</book>

这个例子演示了如何使用 <xsl:attribute> 元素向生成的元素添加属性。


转载请注明出处:http://www.pingtaimeng.com/article/detail/12220/XML