【发布时间】:2015-05-15 13:56:41
【问题描述】:
我想在父标签(<Item>) 和子标签(<Sku>) 中对同名的节点进行分组。
<Item> 标记可能包含许多 <Sku> 子标记,但不应将它们分组,而应将每个 Sku 和 Item 中的元素单独分组。
我有一个如下的输入 xml 文件:
<Products>
<Item>
<Dimensions>
<Height>10</Height>
</Dimensions>
<Dimensions>
<Weight>10</Weight>
</Dimensions>
<Color>
<Attribute>Orange</Attribute>
</Color>
<Color>
<Attribute>Blue</Attribute>
</Color>
<Sku>
<Dimensions>
<Height>10</Height>
</Dimensions>
<Dimensions>
<Weight>10</Weight>
</Dimensions>
<Color>
<Attribute>Orange</Attribute>
</Color>
<Color>
<Attribute>Blue</Attribute>
</Color>
</Sku>
<Sku>
<Dimensions>
<Height>10</Height>
</Dimensions>
<Dimensions>
<Weight>10</Weight>
</Dimensions>
<Color>
<Attribute>Orange</Attribute>
</Color>
<Color>
<Attribute>Blue</Attribute>
</Color>
</Sku>
</Item>
</Products>
预期输出如下:
<Products>
<Item>
<Dimensions>
<Height>10</Height>
<Weight>10</Weight>
</Dimensions>
<Color>
<Attribute>Orange</Attribute>
<Attribute>Blue</Attribute>
</Color>
<Sku>
<Dimensions>
<Height>10</Height>
<Weight>10</Weight>
</Dimensions>
<Color>
<Attribute>Orange</Attribute>
<Attribute>Blue</Attribute>
</Color>
</Sku>
<Sku>
<Dimensions>
<Height>10</Height>
<Weight>10</Weight>
</Dimensions>
<Color>
<Attribute>Orange</Attribute>
<Attribute>Blue</Attribute>
</Color>
</Sku>
</Item>
</Products>
任何帮助将不胜感激。 我在 xslt 下面使用了转换,但它只是“项目”下存在的组合元素。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:key name="elements" match="Item/*[not(self::Sku)]" use="concat(name(), '|', generate-id(..))"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Item">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:for-each select="*[generate-id() = generate-id(key('elements', concat(name(), '|', generate-id(..)))[1])]">
<xsl:copy>
<xsl:apply-templates select="key('elements', concat(name(), '|', generate-id(..)))/*"/>
</xsl:copy>
</xsl:for-each>
<xsl:apply-templates select="Item" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
【问题讨论】:
标签: xslt