Sorting a table in xsl after creation

2019-07-09 02:18发布

I am trying to create a HTML table from two node sets in my XML and then sort it by @AD.

I can sort within individual for-each loops using <xsl:sort select="@AD" order="ascending" />, but I want to sort the whole table.

<xsl:template match="*/Sync/AP">
    <table border="1">
        <tr>
            <th>AD</th>
            <th>GCD</th>
            <th>ClearAttribute</th>
        </tr>
        <xsl:for-each select="./*">
        <tr>
            <td><xsl:value-of select="@AD"/></td>
            <td><xsl:value-of select="@GCD"/></td>
            <td><xsl:value-of select="@ClearAttribute"/></td>
        </tr>       
        </xsl:for-each>
        <!-- Also Append the Common attributes to each region -->
        <xsl:for-each select="../Common/*">
        <tr>
            <td><xsl:value-of select="@AD"/></td>
            <td><xsl:value-of select="@GCD"/></td>
            <td><xsl:value-of select="@ClearAttribute"/></td>
        </tr>       
        </xsl:for-each>
    </table>
</xsl:template>

标签: xml xslt
1条回答
疯言疯语
2楼-- · 2019-07-09 02:55

Don't make two separate <xsl:for-each>. Select all the nodes you want to display and sort them in one step.

The union operator | is used for this:

<xsl:template match="Sync/AP">
    <table border="1">
        <tr>
            <th>AD</th>
            <th>GCD</th>
            <th>ClearAttribute</th>
        </tr>
        <xsl:for-each select="./* | ../Common/*">
            <xsl:sort select="@AD" order="ascending" />
            <tr>
                <td><xsl:value-of select="@AD"/></td>
                <td><xsl:value-of select="@GCD"/></td>
                <td><xsl:value-of select="@ClearAttribute"/></td>
            </tr>       
        </xsl:for-each>
    </table>
</xsl:template>

Note: Even though match expressions look like XPath, they are not really XPath. This is unnecessary:

<xsl:template match="*/Sync/AP">

you can use this instead:

<xsl:template match="Sync/AP">

or even this:

<xsl:template match="AP">

unless you explicitly want to make sure that only <AP> with a <Sync> parent are matched.

查看更多
登录 后发表回答