【发布时间】:2015-02-04 13:49:17
【问题描述】:
我是 xslt 的新手,请帮忙以便为以下 xml 模式编写 xsl。 我想将具有相同名称的元素分组在一个标签下。可以有多个具有相同名称的元素,例如 Shapes、Devices 等。
<?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>
<Device>
<Name>peg</Name>
<type>X11</type>
</Device>
<Device>
<Name>peg1222</Name>
<type>X11111</type>
</Device>
<Utilities>
<Software>QT</Software>
<Platform>Linux</Platform>
</Utilities>
</Screen>
上面的xml文件,我用的是下面的xsl文件
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*">
<xsl:copy>
<Shapes>
<xsl:copy-of select="Shapes/*"/>
</Shapes>
<xsl:apply-templates select="*[name()!='Shapes']"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
输出为
<?xml version="1.0" encoding="UTF-8"?>
<Screen>
<Shapes>
<Triangle id="tri1">
<color>red</color>
<size>large</size>
</Triangle>
<Rectangle id="rec1">
<color>blue</color>
<size>medium</size>
</Rectangle>
</Shapes>
<Device>
<Name>peg</Name>
<type>X11</type>
</Device>
<Device>
<Name>peg1222</Name>
<type>X11111</type>
</Device>
<Utilities>
<Software>QT</Software>
<Platform>Linux</Platform>
</Utilities>
</Screen>
但它仅基于形状进行分组,我不知道有多少元素在 XML 中重复(我们可能会得到另一个重复的元素)。
请让我知道我们是否可以修改上面的 xsl 以适应具有相同名称的动态元素出现的 xml。
【问题讨论】: