编写XSLT以将具有属性名称的XML转换为标记

时间:2015-04-18 06:15:23

标签: xml xslt xpath xml-parsing

我有以下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>

1 个答案:

答案 0 :(得分:4)

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

<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>