aspose file tools*
The moose likes XML and Related Technologies and the fly likes Help needed on XPath question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "Help needed on XPath question" Watch "Help needed on XPath question" New topic
Author

Help needed on XPath question

Elizabeth King
Ranch Hand

Joined: Jul 11, 2002
Posts: 191
What will function count() evaluate to for the given XML document?
count(//child: rder/child::item/preceding-sibling::*)
-------------------XML Document----------------------
<invoice>
<customer> Jim </customer>
<order id="001">
<item>book</item>
<quantity>10</quantity>
</order>
<order id="002">
<date>2001-12-31</date>
<item>CD</item>
<quantity>2</quantity>
</order>
</invoice>
---------------------------------------------
I was told the answer is 1, but why?
Thanks.
Mapraputa Is
Leverager of our synergies
Sheriff

Joined: Aug 26, 2000
Posts: 10065
First, "child::" axis is default and your expression can be simpler written as
//order/item/preceding-sibling::*
Now
//order - select all elements with the name "order". On this step two elements are selected.
/item - go one step down the hierarchical tree and select "item" elements that are children of "order" element. Again two elements are selected.
/preceding-sibling::*
now select all elements that are on the same hierarchical level with already found "items" and precede them. In our case it will be
<date>2001-12-31</date>
under
<order id="002">
So the count() function returns 1
If we modified your example as
<order id="002">
<date>2001-12-31</date>
<item>CD1</item>
<item>CD</item>
<quantity>2</quantity>
</order>
then
<date>2001-12-31</date>
<item>CD1</item>
would be selected and the count() function would return 2.
There is a great tool for such kind of experiments: XPath Visualizer. You can enter parts of your XPath expression and see which nodes are selected. What I like most about this tools, it's built with XSLT and HTML, so you do not need to spend hours downloading xxx MB, the whole tool is 30KB (KB, not MB), 360Kb unziped
--------------------
Map, who recently had to download 53MB of IBM software to encrypt 10 bytes in an XML document.
Elizabeth King
Ranch Hand

Joined: Jul 11, 2002
Posts: 191
Thanks, Mapraputa.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Help needed on XPath question