Reputation: 227
I have an xml structure that looks like this:
<document>
<body>
<section>
<title>something</title>
<subtitle>Something again</subtitle>
<section>
<p xml:id="1234">Some text</p>
<figure id="2121"></figure>
<section>
<p xml:id="somethingagain">Some text</p>
<figure id="939393"></figure>
<p xml:id="countelement"></p>
</section>
</section>
</section>
<section>
<title>something2</title>
<subtitle>Something again2</subtitle>
<section>
<p xml:id="12345678">Some text2</p>
<figure id="939394"></figure>
<p xml:id="countelement2"></p>
</section>
</section>
</body>
</document>
How can I count the figure elemtens I have before the <p xml:id="countelement"></p>
element using XPath?
Edit: And i only want to count figure elements within the parent section, in the next section it should start from 0 again.
Upvotes: 0
Views: 5001
Reputation: 4806
count(id("countelement")/preceding-sibling::figure)
Please note that the xml:id
attributes of two different elements cannot the same value, such as "countelement". If you wish two different elements to have a same-named attribute with the same value "countelement", it must be some other attribute perhaps "kind" that is not of DTD attribute type ID. In that case in place of id("countelement")
you would use *[@kind="countelement"]
.
Upvotes: 0
Reputation: 38662
Given you're using an XPath 2.0 compatible engine, find the count element and call fn:count()
for each of them with using all preceding figure-elements as input.
This will return the number of figures preceding each "countelement" on the same level (I guess this is what you actually want):
//p[@xml:id="countelement"]/count(preceding-sibling::figure)
This will return the number of figures preceding each "countelement" and the level above:
//p[@xml:id="countelement"]/count(preceding-sibling::figure | parent::*/preceding-sibling::figure)
This will return the number of all preceeding figures preceding each "countelement" and the level above:
//p[@xml:id="countelement"]/count(preceding::figure)
If you're bound to XPath 1.0, you won't be able to get multiple results. If @id
really is an id (and thus unique), you will be able to use this query:
count(//p[@xml:id="countelement"]/preceding::figure)
If there are "countelements" which are not <p/>
elements, replace p
by *
.
Upvotes: 1