简体   繁体   中英

How can I match the first element in the document using XSLT?

this is a follow up for How can I select the first element using XSLT? .

<xml>
    <news>
        <newsitem>
            <dateCreated>2009-09-09</dateCreated>
            <summary>Something great happened</sumamry>
        </newsitem>
        <newsitem>
            <dateCreated>2009-09-08</dateCreated>
            <summary>Something bad happened</sumamry>
        </newsitem>
    </news>
    <news>
        <newsitem>
            <dateCreated>2009-09-07</dateCreated>
            <summary>Something really bad happened</sumamry>
        </newsitem>
    </news>
</xml>

How can I match against the first newsitem element in the document? the xsl:template match="//newsItem[1]" match sujested in the other question will get the first child. xsl:template match="(//newsItem)[1]" is not valid. The only other hints I've gotten involves doing some complicated/messy stuff with keys, it seems like there should be a better answer,

如果我理解这个问题,我认为您应该使用:

<xsl:template match="//news[1]/newsitem[1]"> to select the first item of all.

There's no simple match pattern that will select the first element of name newsitem in the document. You can do it with a predicate:

match="newsitem[not(preceding::newsitem)]"

but the performance is likely to be horrible.

With XSLT 2.0 the best solution is to bind a global variable and test for it:

<xsl:variable name="first-newsitem" select="(//newsitem)[1]"/>

<xsl:template match="newsitem[. is $first-newsitem]"/>

在XSLT 1.0中,可以使用以下命令

newsitem[not(ancestor::newsitem or preceding::newsitem)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM