代码之家  ›  专栏  ›  技术社区  ›  badbee

使用xsl:sort时保留未排序元素的问题

  •  0
  • badbee  · 技术社区  · 8 月前

    我的xsl:sort正在按预期排序,但没有给出所需的输出。

    这是我的示例输入xml

    <ns3:ASC858_004010 xmlns:ns3="http://sap.com">
    <root>
        <name1/>
        <name2/>
        <loops>
            <name3/>
            <loop mode="2">
                <counter>2</counter>
            </loop>
            <loop mode="1">
                <counter>1</counter>
            </loop>
            <name4/>
        </loops>
        <name5/>
    </root>
    </ns3:ASC858_004010>
    

    我的xslt是:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <xsl:output method="xml" indent="yes"/>
    
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="loops">
        <xsl:copy>
            <xsl:apply-templates select="loop">
                <xsl:sort select="counter"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
    
    </xsl:stylesheet>
    
    

    我得到了

    <ns3:ASC858_004010 xmlns:ns3="http://sap.com">
    <root>
        <name1/>
        <name2/>
        <loops>
            <loop mode="1">
                <counter>1</counter>
            </loop>
            <loop mode="2">
                <counter>2</counter>
            </loop>
        </loops>
        <name5/>
    </root>
    </ns3:ASC858_004010>
    

    我想要的输出是

    <ns3:ASC858_004010 xmlns:ns3="http://sap.com">
    <root>
        <name1/>
        <name2/>
        <loops>
            <name3/>
            <loop mode="1">
                <counter>1</counter>
            </loop>
            <loop mode="2">
                <counter>2</counter>
            </loop>
            <name4/>
        </loops>
        <name5/>
    </root>
    </ns3:ASC858_004010>
    

    名字3和名字4的位置不见了。我只是把name3和name4作为一个示例,但在“循环”中的“循环”结构之前和之后可能还有更多的元素。

    我错过了什么?

    1 回复  |  直到 8 月前
        1
  •  1
  •   Martin Honnen    8 月前

    使用例如。

    <xsl:template match="loops">
        <xsl:copy>
            <xsl:apply-templates select="loop[1]/preceding-sibling::*"/>
            <xsl:apply-templates select="loop">
                <xsl:sort select="counter"/>
            </xsl:apply-templates>
            <xsl:apply-templates select="loop[last()]/following-sibling::*"/>
        </xsl:copy>
    </xsl:template>
    

    如果只有非 loop 前后元素 元素,但不在两者之间。

    推荐文章