Returning XPath correct order ( insted of document

2020-03-06 06:33发布

So ive been given an assignment in my university of "fixing" XPath and get it to return the nodes in the correct order.

Ive been trying to find a way around writing a very long code and breaking each expression into little peaces and putting it back together again.

Ive thought of a few ideas but i need help making them happen :)

  1. Find the method in the XPath jar that sorts the nodes and delete it - problem is i dont know if its possible to see the XPath jar code , and didnt find it online.- if you can point me to it , that would be great !

  2. Ive found this option which looks like it should do the trick http://cafeconleche.org/books/xmljava/chapters/ch16s06.html
    but it demands dom implementation of XPath 3.0 and i cant find that dom anywhere - any idea if there is such thing ?

  3. If you have any other idea i would love to hear !

For example : for this xml

 <library> 
 <book name="book1"> 
  hello 
 </book> 
 <book name="book2"> 
  world 
 </book>
 <book name="book3">
  !!! 
 </book>
 </library>

and this expression : /library/book[3]/preceding-sibling::book Im getting

book1 book2

insted of :

book2 book1

I can use anything as long as i do it in a java program

Thank you for all your help :)

标签: java xpath
1条回答
叛逆
2楼-- · 2020-03-06 07:17

In XPath 1.0, there are no node sequences, only node sets. The XPath 1.0 specification doesn't define the order of nodes in a node set. Many APIs don't define it either, but invariably they return the nodes in the node-set in document order - not because XPath requires it, but because XSLT requires it, and XSLT has set the expectations for how XPath engines should behave.

If you want node sequences with control over the ordering, you will have to move to XPath 2.0 (or XQuery 1.0, which is a superset of XPath 2.0). In XPath 2.0, the following expression returns what you want:

reverse(/library/book[3]/preceding-sibling::book)
查看更多
登录 后发表回答