How to sort based on different nodes?

心已入冬 提交于 2019-12-25 01:54:13

问题


I need to sort my tags in a XML file based on multiple different nodes. For example: Consider the following XML:

<root>
    <a>
        <b>12</b>
        <e>hello</e>
    </a> 
    <a>
        <b>11</b>
        <e>how</e>
    </a>
    <a>
        <c>13</c>
        <f>are</f>
    </a>
    <a>
        <b>21</b>
        <f>you</f>
    </a>
    <a>
        <d>22</d>
        <e>hello</e>
    </a>
    <a>
        <c>14</c>
        <f>hi</f>
    </a>
</root>

Now I need to find the maximum number from inside all the nodes inside a. I tried doing this:

<xsl:template match="root">
    <xsl:for-each select="a">
        <xsl:sort select="b | c | d" data-type="number" order="descending"/>   <!-- this gives me error-->
            <xsl:if test="position() = 1">
                <!-- how to access my node -->
            </xsl:if>
    </xsl:for-each>
</xsl:template>

How can I do my sorting and get the value form the first node after sorting?

Thnx in advance!!

Note: I am using XSLT 1.0.


回答1:


This stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="root">
        <xsl:for-each select="a/*[string(number(.))!='NaN']">
            <xsl:sort select="." order="descending"/>
            <xsl:if test="position() = 1">
                <highest><xsl:copy-of select="."/></highest>
            </xsl:if>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

when applied to the edited input XML above, outputs

<highest>
   <d>22</d>
</highest>


来源:https://stackoverflow.com/questions/22602178/how-to-sort-based-on-different-nodes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!