2

使用根节点选择和使用文档对象选择节点有什么区别?首选哪种方式。

例如,

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");
4

3 回答 3

1

事实上,我从来没有任何分歧。并且只使用

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

因为如果文档的根存在

bool b = Doc.OuterXml == Doc.DocumentElement.OuterXml; // true
于 2010-11-13T09:31:13.110 回答
1

由于XPath//表达式总是从文档根开始匹配,因此无论您从文档根开始还是从它的documentElement.

所以我猜你最好使用更短的Doc.SelectNodes("//@id");语法。

于 2010-11-13T09:33:42.297 回答
1

XML 文档的根至少包含它的文档元素,但它也可能包含处理指令和注释。例如,在这个 XML 文档中:

<!-- 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 -->

根有三个子节点,其中一个是它的顶级元素。在这种情况下,这个:

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

还有这个:

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

返回完全不同的结果。

于 2010-11-13T21:53:36.337 回答