XmlDocument.SelectNodes 问题

发布于 2024-10-02 05:40:56 字数 375 浏览 0 评论 0原文

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

例如,

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

任谁 2024-10-09 05:40:56

事实上,我从来没有发现任何差异。并使用只是

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

因为如果文档的根存在

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

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
给妤﹃绝世温柔 2024-10-09 05:40:56

由于 XPath// 表达式始终与文档匹配root,无论您从文档根还是从其 documentElement 开始,结果都是相同的。

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

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.

骑趴 2024-10-09 05:40:56

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

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

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

和 this:

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

返回完全不同的结果。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文