1

我有一些看起来像这样的 xml 片段

<an_element1 attribute1="some value" attribute2="other value" ... attributeN="N value">
<an_element2 attribute1="some value" attribute2="other value" ... attributeN="N value">
...

我需要把它改成这样:

<an_element1>
<attribute1>some value</attribute1>
<atttibute2>other value</attribute2>
...
<attributeN>N value</attributeN>
</an_element1>
<an_element2>
<attribute1>some value</attribute1>
<atttibute2>other value</attribute2>
...
<attributeN>N value</attributeN>
</an_element2>
...

我已经成功地尝试了在其他答案中找到的一些示例,但我想知道是否有一种通用方法可以解决这个问题,可以这样总结:

为每个名为 an_element 的元素为其每个属性创建一个子元素,每个属性都包含它们各自的值。

由于重复元素可能包含重复值(两个 an_element 项目的所有属性都具有相同的值),我想知道是否可以仅过滤唯一元素。

如果过滤器是可能的,最好在转换之前或之后应用它?

4

1 回答 1

1

为每个名为 an_element 的元素为其每个属性创建一个子元素,每个属性都包含它们各自的值。

以下样式表将所有属性转换为同名元素。从属性生成的元素将优先于从源中的子元素复制的元素。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XST/Transform" version="1.0">
  <xsl:template match="@*">
    <xsl:element name="{name()}">
      <xsl:value-of select="."/>
    </xsl:element>
  </xsl:template>

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

如果您只想对具有特定名称的元素执行此操作,则需要更像

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XST/Transform" version="1.0">
  <xsl:template match="an_element/@*">
    <xsl:element name="{name()}">
      <xsl:value-of select="."/>
    </xsl:element>
  </xsl:template>

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

这将转换

<an_element foo="bar"/>

进入

<an_element>
  <foo>bar</foo>
</an_element>

但会<another_element attr="whatever"/>保持不变。

于 2013-03-04T14:04:32.747 回答