user2075124
user2075124

Reputation: 227

xpath: count elements in XML document

I have a fairly large XML document. The basic structure of that XML is as follows:

<document>
    <title>
        Title
    </title>
    <frontm>
        <toc>
        </toc>
    </frontm>
    <body>
        <section>
            <section>
                <p>content</p>
            </section>
        </section>
        <section>
            <section>
                <p>content</p>
            </section>
        </section>
        <section>
            <section>
                <p>content</p>
            </section>
        </section>
        <section>
            <section>
                <p>content</p>
            </section>
        </section>
    </body>
</document>

I have tried the following xpath but it returns just half the number of sections:

count(../../body/section/section/following-sibling::node())+1

Any ideas?

Edit: I am trying to count the number of sections in sections (applied to the example above, the xpath should return 4).

Upvotes: 0

Views: 3818

Answers (1)

StuartLC
StuartLC

Reputation: 107367

It seems you want to count the section elements

If you want to count the leaf node sections without making assumptions about p children

count(//section[ancestor::section])

Similarly, if you want to count the parent sections

count(//section[section])

And if you want to count all section elements, at any level:

count(//section)

Upvotes: 1

Related Questions