我可以看到许多类似问题的答案,但我似乎无法让它们为我工作。我有一些 xml 文件,其中一些兄弟元素节点具有相同的标签名称。我想使用 XSLT 合并这些节点。任何帮助将不胜感激。
输入:
<?xml version="1.0"?>
<Screen>
<Shapes>
<Triangle id="tri1">
<color>red</color>
<size>large</size>
</Triangle>
</Shapes>
<Shapes>
<Rectangle id="rec1">
<color>blue</color>
<size>medium</size>
</Rectangle>
</Shapes>
<Shapes>
<Circle id="cir1">
<color>green</color>
<size>small</size>
</Circle>
</Shapes>
<Shapes>
<Square id="sqr1">
<color>yellow</color>
<size>large</size>
</Square>
</Shapes>
<Device>
<Name>peg</Name>
<type>X11</type>
</Device>
<Utilities>
<Software>QT</Software>
<Platform>Linux</Platform>
</Utilities>
</Screen>
我想合并所有“形状”节点。 所需输出
<?xml version="1.0"?>
<Screen>
<Shapes>
<Triangle id="tri1">
<color>red</color>
<size>large</size>
</Triangle>
<Rectangle id="rec1">
<color>blue</color>
<size>medium</size>
</Rectangle>
<Circle id="cir1">
<color>green</color>
<size>small</size>
</Circle>
<Square id="sqr1">
<color>yellow</color>
<size>large</size>
</Square>
</Shapes>
<Device>
<Name>peg</Name>
<type>X11</type>
</Device>
<Utilities>
<Software>QT</Software>
<Platform>Linux</Platform>
</Utilities>
</Screen>
我试过的 XSLT 是:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output indent="yes" />
<xsl:template match="Shapes">
<xsl:if test="not(preceding-sibling::*[local-name() = 'Shapes'])">
<Shapes>
<xsl:apply-templates select="node() | @*" />
<xsl:apply-templates select="following-sibling::*[local-name() = 'Shapes']" />
</Shapes>
</xsl:if>
<xsl:if test="preceding-sibling::*[local-name() = 'Shapes']">
<xsl:apply-templates select="node() | @*" />
</xsl:if>
</xsl:template>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
但我得到的输出是(:()
<Screen>
<Shapes>
<Triangle id="tri1">
<color>red</color>
<size>large</size>
</Triangle>
<Rectangle id="rec1">
<color>blue</color>
<size>medium</size>
</Rectangle>
<Circle id="cir1">
<color>green</color>
<size>small</size>
</Circle>
<Square id="sqr1">
<color>yellow</color>
<size>large</size>
</Square>
</Shapes>
<Rectangle id="rec1">
<color>blue</color>
<size>medium</size>
</Rectangle>
<Circle id="cir1">
<color>green</color>
<size>small</size>
</Circle>
<Square id="sqr1">
<color>yellow</color>
<size>large</size>
</Square>
<Device>
<Name>peg</Name>
<type>X11</type>
</Device>
<Utilities>
<Software>QT</Software>
<Platform>Linux</Platform>
</Utilities>
</Screen>
是否有我可以使用的简单 XSLT 代码,或者我的 xslt 中是否有任何修改可以应用以获取输出?