首页 > 解决方案 > 使用 XSLT 1.0 的 xml 消息中的元素对相邻段进行排序

问题描述

我是 XSLT 的新手。我需要帮助来实现以下输出。我将使用以下示例解释我的要求:

输入:

<library>
<Name>aaaaa</Name>
<Street>wwww</Street>
<Country>qqqq</Country>
<stock>
    <book>
        <Details>
            <Ranking>3</Ranking>
            <Title>abc3</Title>
            <Author>hhhhh3</Author>
        </Details>
    </book>
    <book>
        <Details>
            <Ranking>2</Ranking>
            <Title>abc2</Title>
            <Author>hhhhh2</Author>
        </Details>
    </book>
    <book>
        <Details>
            <Ranking>1</Ranking>
            <Title>abc1</Title>
            <Author>hhhhh1</Author>
        </Details>
    </book>
    <book>
        <Details>
            <Ranking>4</Ranking>
            <Title>abc4</Title>
            <Author>hhhhh4</Author>
        </Details>
    </book>
</stock>

输出:

  <library>
    <Name>aaaaa</Name>
    <Street>wwww</Street>
    <Country>qqqq</Country>
<stock>
    <book>
        <Details>
            <Ranking>1</Ranking>
            <Title>abc1</Title>
            <Author>hhhhh1</Author>
        </Details>
    </book>
    <book>
        <Details>
            <Ranking>2</Ranking>
            <Title>abc2</Title>
            <Author>hhhhh2</Author>
        </Details>
    </book>
    <book>
        <Details>
            <Ranking>3</Ranking>
            <Title>abc3</Title>
            <Author>hhhhh3</Author>
        </Details>
    </book>
    <book>
        <Details>
            <Ranking>4</Ranking>
            <Title>abc4</Title>
            <Author>hhhhh4</Author>
        </Details>
    </book>
</stock>

“书”段需要使用 XSLT 1.0 基于“排名”按升序排序。

我尝试了排序功能,但如果所有“详细信息”都在一本“书”中,则可以使用。我尝试了很多其他的东西,但没有成功。有人可以帮帮我吗 ?

标签: xslt

解决方案


<xsl:output method="html" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="stock">
        <xsl:copy>

                <xsl:for-each select="book">

                    <xsl:sort order="ascending" select="Details/Ranking"/>
                    <xsl:copy-of select="."/>

                </xsl:for-each>

        </xsl:copy>
    </xsl:template>
Try it

推荐阅读