Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help needed on XPath question

 
Elizabeth King
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10065
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Mapraputa.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic