开发者

Get element position() regardless of parent

Lets say you have an xml document like

<parents>
    <parent>
        <element />
        <element />
    </parent>
    <parent>
        <element />
        <element />
    </parent>
</parents>

While processing I need to know that the elements are 1, 2, 3, 4 in the document, not that but calling position() will return 1, 2, 1, 2. Normally I would modify the xml, but, in this case, it is not possible, while I am processing parent 2, I somehow need to know that it's first element, is really element 3.开发者_JS百科

Thanks, -c


Use <xsl:number>

This transformation:

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

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="element">
     <xsl:copy>
       <xsl:number level="any" count="element"/>
     </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<parents>
    <parent>
        <element />
        <element />
    </parent>
    <parent>
        <element />
        <element />
    </parent>
</parents>

produces the wanted result:

<parents>
    <parent>
        <element>1</element>
        <element>2</element>
    </parent>
    <parent>
        <element>3</element>
        <element>4</element>
    </parent>
</parents>


Got it, it's actually quite simple

<xsl:value-of select="count(preceding::element)"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜