【问题标题】:Writing XSLT to transform XML with attribute names into tags编写 XSLT 以将带有属性名称的 XML 转换为标签
【发布时间】:2015-04-18 06:15:22
【问题描述】:

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

【问题讨论】:

  • 只有当name 属性的值始终是有效的元素名称时,您的要求才是可能的。

标签: xml xslt xpath xml-parsing


【解决方案1】:

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

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

【讨论】:

  • 非常感谢您提供正确的链接和 cmets Eero。效果很好!
  • @Meow:很高兴听到它有帮助。为了子孙后代的利益,请考虑accepting the answer
猜你喜欢
  • 2014-12-21
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
相关资源
最近更新 更多