Question

What's the difference using root node to select and using document object to select nodes? Which way is preferred.

For example,

1.

XmlDocument Doc = new XmlDocument();
Doc.Load(mem);

XmlNodeList nodeList = Doc.SelectNodes(@"//@id");

2.

XmlDocument Doc = new XmlDocument();
Doc.Load(mem);

XmlElement root = Doc.DocumentElement;

XmlNodeList nodeList = root.SelectNodes(@"//@id");
Was it helpful?

Solution

In fact, I never got any differences. And use just

Doc.SelectNodes(@"//@id");

because if document's root exists

bool b = Doc.OuterXml == Doc.DocumentElement.OuterXml; // true

OTHER TIPS

Since XPath's // expression always matches from the document root, the result will be the same whether you start from the document root or from its documentElement.

So I guess you're better off using the shorter Doc.SelectNodes("//@id"); syntax.

The root of an XML document contains its document element at least, but it may also contain processing instructions and comments. For instance, in this XML document:

<!-- This is a child of the root -->
<document_element>
   <!-- This is a child of the document element -->
<document_element>
<!-- This is also a child of the root -->

the root has three child nodes, one of which is its top-level element. In this case, this:

XmlNodeList comments = doc.SelectNodes("comment()");

and this:

XmlNodeList comments = doc.DocumentElement.SelectNodes("comment()");

return totally different results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top