我有这样一个xml示例,
<doc>
<aa type="aaa" id="ggg">text</aa>
<aa type="bbb" id="hhh">text</aa>
<aa type="ccc" id="iii">text</aa>
<aa type="ccc" id="jjj">text</aa>
<aa type="bbb" id="kkk">text</aa>
<aa type="aaa" id="lll">text</aa>
</doc>正如您所看到的,这里有两个元素存在着相等的type属性,如果类型属性相等的元素,我需要交换id属性值。
所以,对于上面的例子,输出应该是,
<doc>
<aa type="aaa" id="lll">text</aa>
<aa type="bbb" id="kkk">text</aa>
<aa type="ccc" id="jjj">text</aa>
<aa type="ccc" id="iii">text</aa>
<aa type="bbb" id="hhh">text</aa>
<aa type="aaa" id="ggg">text</aa>
</doc>我在xsl之后写了这样的文章,
<xsl:template match="aa[@type='aaa' or @type='bbb' or @type='ccc'][1]">
<xsl:copy>
<xsl:if test="following::aa[@type=self::node()/@type]">
<xsl:attribute name="id">
<xsl:value-of select="following::aa[@type=self::node()/@type]/@type"/>
</xsl:attribute>
</xsl:if>
</xsl:copy>
</xsl:template>
<xsl:template match="aa[@type='aaa' or @type='bbb' or @type='ccc'][2]">
<xsl:copy>
<xsl:if test="following::aa[@type=self::node()/@type]">
<xsl:attribute name="id">
<xsl:value-of select="preceding::aa[@type=self::node()/@type]/@type"/>
</xsl:attribute>
</xsl:if>
</xsl:copy>
</xsl:template>但这并不像预期的那样,有人建议我如何使用XSLT来完成这个任务?
发布于 2016-02-11 07:01:33
试试这个
<xsl:stylesheet
version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:output indent="yes" omit-xml-declaration="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="aa">
<xsl:variable name="type" select="@type"/>
<xsl:copy>
<xsl:apply-templates select="@type"/>
<xsl:choose>
<xsl:when test="following::aa[@type=$type]">
<xsl:attribute name="id">
<xsl:value-of select="following::aa[@type=$type]/@id"/>
</xsl:attribute>
</xsl:when>
<xsl:when test="preceding::aa[@type=$type]">
<xsl:attribute name="id">
<xsl:value-of select="preceding::aa[@type=$type]/@id"/>
</xsl:attribute>
</xsl:when>
</xsl:choose>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>https://stackoverflow.com/questions/35331436
复制相似问题