xmldocument.SelectNodes问题
-
09-10-2019 - |
题
使用root节点选择和使用文档对象选择节点有什么区别?首选哪种方式。
例如,
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");
解决方案
实际上,我从未有任何差异。并使用
Doc.SelectNodes(@"//@id");
因为如果文档的根源存在
bool b = Doc.OuterXml == Doc.DocumentElement.OuterXml; // true
其他提示
自从 XPATH' //
表达式始终匹配文档root,无论您是从文档root还是从其启动开始的,结果都将相同 documentElement
.
所以我想你最好使用较短的 Doc.SelectNodes("//@id");
句法。
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()");
返回完全不同的结果。
不隶属于 StackOverflow