3
4

2 回答 2

4

The | operator computes the union of its operands and with XPath 1.0 you simply get a set of nodes, the order is undefined, though most XPath APIs then return the result in document order or allow you to say which order you want or whether order matters (see for instance http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult).

With XPath 2.0 you get a sequence of nodes ordered in document order, with XPath 2.0 if you want the order of your subexpressions you would need to use the comma operator, not the union operator i.e. element[@attr="a"] , element[@attr="b"] , element[@attr="c"].

于 2012-10-06T11:34:21.243 回答
4

can I create an expression that guarantees the result to appear in the order as in the query, even if the elements appear in a different order in the document?

  1. Not with any XPath 1.0 engine -- they return the resulting XmlNodeList in document order.

  2. With XPath 2.0 one can specify that a sequence is to be returned, using the comma , operator, like this:

    element[@attr="a"] , element[@attr="b"] , element[@attr="c"]

  3. Finally, If you are limited with an XPath 1.0 implementation, one way of getting the results in the desired order is to evaluate these three XPath expressions:

    element[@attr="a"]

    element[@attr="b"]

    element[@attr="c"]

Then you can access the first result first, the second result -- second and the third result -- third.

于 2012-10-06T16:39:54.203 回答