编写 XSLT 将带有属性名称的 XML 转换为标签

Writing XSLT to transform XML with attribute names into tags

我有以下 XML 输入:

<?xml version="1.0" encoding="utf-8"?>

<update-all-attributes>
  <document name="http://www.threadless.com/product/8/Ctrl_Z">
    <attribute name="PageType" value="product" />
    <attribute name="ProductId" value="8" />
    <attribute name="Title" value="Ctrl + Z"></attribute>
  </document>

如何编写 XSLT 查询以将其转换为下面的 XML 解析属性名称并从中创建标签?

<?xml version="1.0" encoding="utf-8"?>

<update-all-attributes>
  <document name="http://www.threadless.com/product/8/Ctrl_Z">
    <PageType>product</PageType>
    <ProductId>8</ProductId>
    <Title>Ctrl + Z</Title>
  </document>

这个非常简单的样式表应该可以解决问题:

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

  <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

  <!-- Identity template: http://en.wikipedia.org/wiki/Identity_transform#Using_XSLT -->
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- Match any <attribute> element -->
  <xsl:template match="attribute">
    <!--
    Create a new element, using the @name attribute of the current element as
    the element name. The curly braces {} signify attribute value templates:

    http://lenzconsulting.com/how-xslt-works/#attribute_value_templates
    -->
    <xsl:element name="{@name}">
      <!-- Use the value of the @value attribute as the content of the new element -->
      <xsl:value-of select="@value"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>