开发者

How do I guarantee node order for an XPath 'OR' query

开发者 https://www.devze.com 2023-02-01 02:15 出处:网络
I have a snippet of XML that looks like <body> Some text.... <nodeA>....</nodeA> more text

I have a snippet of XML that looks like

<body>
   Some text....
   <nodeA>....</nodeA>
   more text
   <someOtherNode>
      <nodeA>.......</nodeA>
   </someOtherNode>
   <nodeB>.......</nodeB>  
   et开发者_如何学Goc.....
</body>

I'm selecting all nodeA and NodeB nodes inside <body> using an XPATH query similar to //nodeA|//nodeB

As I understand it, .NET supports XPath 1.0 which does not guarantee node order.

How can I guarantee selected nodes are returned in document order in my OR query : that's to say:

nodeA, nodeA, nodeB   


As I understand it, .NET supports XPath 1.0 which does not guarantee node order

When an XPath 1.0 expression that selects nodes is evaluated, the selected nodes form a node-set. A node-set is a set and this, among many other things, means that it is unordered.

For practical purposes, though, there is one main ordering chosen to enumerate the nodes of a node set: document order. In practice, all XPath 1.0 engines I know (and certainly in .NET) return the selected nodes in document order. In the future this is unlikely to change, because vendors try to preserve backwards compatibility.

Therefore, just try using the SelectNodes() or Evaluate() methods and verify that the nodes in the results are in document order.

Do note: The order of the following cannot be guaranteed and is implementation-dependent:

  1. Attributes of the same element.

  2. Nodes belonging to different documents (a node-set containing nodes from different documents can be produced using the XSLT function document(), so this most probably is of no concern to you).


You have to sort the nodes outside of XPath. So iterate through the nodes in the node-set and add them to a collection, which you then sort using XPathNavigator.ComparePosition for comparisons.

Either that or use an XPath 2.0 implementation for .NET

0

精彩评论

暂无评论...
验证码 换一张
取 消