使用根节点选择和使用文档对象来选择节点有什么区别? 哪种方式更受欢迎。
例如,
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");
答案 0 :(得分:1)
事实上,我从来没有任何分歧。并使用
Doc.SelectNodes(@"//@id");
因为如果文档的根存在
bool b = Doc.OuterXml == Doc.DocumentElement.OuterXml; // true
答案 1 :(得分:1)
由于XPath的//
表达式始终与文档根目录匹配,因此无论您是从文档根目录还是从documentElement
开始,结果都是相同的。
所以我猜你最好使用较短的Doc.SelectNodes("//@id");
语法。
答案 2 :(得分: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 -->
root有三个子节点,其中一个是顶级元素。在这种情况下,这:
XmlNodeList comments = doc.SelectNodes("comment()");
和此:
XmlNodeList comments = doc.DocumentElement.SelectNodes("comment()");
返回完全不同的结果。