views:

348

answers:

2

This is an example xml from MSDN

<?xml version="1.0"?>
<!-- A fragment of a book store inventory database -->
<bookstore xmlns:bk="urn:samples">
  <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8">
    <title>Pride And Prejudice</title>
  </book>
  <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1">
    <title>The Handmaid's Tale</title>
  </book>
  <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6">
    <title>Emma</title>
  </book>
  <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3">
    <title>Sense and Sensibility</title>
  </book>
</bookstore>

When I select all book nodes using the following code, which order will these nodes have?

XmlDocument doc = new XmlDocument();
doc.Load("booksort.xml");

var nodeList =doc.SelectNodes("bookstore/book");

Will the order of the items in the nodelist be the same as the order in the xml? Is this order guaranteed?

A: 

Try using XPathNavigator instead of just XmlDocument.Select*. Then you may create an XPathExpression instance and make it sorted via AddSort.

Mr.Cat
In my usecase, there is no information I can use to sort them. They need to be in the same order as in the xml.
crauscher
Other comments here claim that SelectNodes return nodes in document order (I wonder whether it is true for xpath unions), but I've never come across any guarantees in msdn.XPath 1.0 specs don't seem to guarantee the order as well (you may want to see this link: http://lists.xml.org/archives/xml-dev/200410/msg00005.html).
Mr.Cat
+2  A: 

Yes. Looking at it in reflector this method ends up using an XPathNodeIterator which is documented to iterate in document order. http://msdn.microsoft.com/en-us/library/1212yhbf.aspx

Martin Smith