Reputation: 86085
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");
Upvotes: 2
Views: 1876
Reputation: 96722
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.
Upvotes: 1
Reputation: 100258
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
Upvotes: 1
Reputation: 262939
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.
Upvotes: 1