Page 1 of 1

Counting level of grandparent nodes

Posted: Fri Feb 29, 2008 8:31 pm
by mlcook
I have an element structure like the one below.

When processing "F" elements, I'd like to count which "C" element I'm in when processing each "F".

I think this would be like counting previous "C" siblings when processing "F", but I can't figure out the XPath pattern to give me such a count, or something similar, when in the XSL processing for each "F" element.

I can live with 0-based or 1-based counting, as long as values are sequential.

Thanks for suggestions.

-- Mike

Code: Select all

<C>
<D>
<E Attr1="..." />
<F Attr2="..." /> <!--"C" level would be 0 (or 1) -->
</D>
</C>

<C>
<D>
<E Attr1="..." />
<F Attr2="..." /> <!--"C" level would be 1 (or 2) -->
</D>
</C>

<C>
<D>
<E Attr1="..." />
<F Attr2="..." /> <!--"C" level would be 2 (or 3) -->
</D>
</C>

Re: Counting level of grandparent nodes

Posted: Mon Mar 03, 2008 5:09 pm
by jkmyoung
?maybe
<xsl:value-of select="count(preceding::C)"/>

Re: Counting level of grandparent nodes

Posted: Mon Mar 03, 2008 6:02 pm
by mlcook
I just get '0' for each "F" element processed.

count(preceding-sibling::C) did no better.

Thanks, Mike

Re: Counting level of grandparent nodes

Posted: Mon Mar 03, 2008 6:51 pm
by george
Note that the suggestion was to use preceding::C and not precedinf-sibling::C.

On a document like

Code: Select all


<?xml version="1.0" encoding="UTF-8"?>
<test>
<C>
<D>
<E Attr1="..."></E>
<F Attr2="..."></F>
<!--"C" level would be 0 (or 1) -->
</D>
</C>

<C>
<D>
<E Attr1="..."></E>
<F Attr2="..."></F>
<!--"C" level would be 1 (or 2) -->
</D>
</C>

<C>
<D>
<E Attr1="..."></E>
<F Attr2="..."></F>
<!--"C" level would be 2 (or 3) -->
</D>
</C>
</test>
the following stylesheet

Code: Select all


<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="/">
<result><xsl:apply-templates/></result>
</xsl:template>
<xsl:template match="F">
<inF>Processing F having count of preceding Cs: <xsl:value-of select="count(preceding::C)"/></inF>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
will produce

Code: Select all


<?xml version="1.0" encoding="utf-8"?>
<result>
<inF>Processing F having count of preceding Cs: 0</inF>
<inF>Processing F having count of preceding Cs: 1</inF>
<inF>Processing F having count of preceding Cs: 2</inF>
</result>
Regards,
George

Re: Counting level of grandparent nodes

Posted: Mon Mar 03, 2008 7:12 pm
by mlcook
Dear jkmyoung and George,

In trying to simplify my example, I simplified too much. Please note that I did try preceding as well as preceding-sibling in my first try.

My error: Namespaces!

I needed count(preceding::mynamespace:C)

Sorry about the confusion, and many thanks for your patience as you steered me to the solution.

Thanks again, and apologies,
Mike