[英]XSLT - copy attribute by comparing other element attribute
I have a sample xml like this, 我有一个这样的示例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>
As you can see there are 2 elements exist with equal type
attribute here and what I need is interchange the id
attribute values if elements where type attribute is equal. 如您所见,这里存在2个具有相等type
属性的元素,并且如果类型属性相等的元素,我需要交换id
属性值。
so, for above example, output should be, 因此,对于上面的示例,输出应为
<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>
I've written following xsl to do this, 我已经按照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>
but this doesn't as expected, any anyone suggest me a method how can I do this using XSLT? 但这与预期的不同,任何人都建议我一种方法,如何使用XSLT做到这一点?
try this one 试试这个
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.