首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XSLT -通过比较其他元素属性复制属性。

XSLT -通过比较其他元素属性复制属性。
EN

Stack Overflow用户
提问于 2016-02-11 05:28:33
回答 1查看 402关注 0票数 0

我有这样一个xml示例,

代码语言:javascript
复制
<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属性值。

所以,对于上面的例子,输出应该是,

代码语言:javascript
复制
<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之后写了这样的文章,

代码语言:javascript
复制
<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来完成这个任务?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-11 07:01:33

试试这个

代码语言:javascript
复制
<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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35331436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档