gpt4 book ai didi

.Net 命名表(命名空间)问题

转载 作者:行者123 更新时间:2023-12-04 16:56:45 27 4
gpt4 key购买 nike

在 .Net 中,我这样做:

XmlNamespaceManager nsMan = new XmlNamespaceManager(xmlDoc.NameTable);
XmlNodeList nlImages = xmlDoc.SelectNodes("//v:imagedata", nsMan);

我得到这个异常(exception):
Namespace prefix 'v' is not defined.

但是如果我打破这个过程并写下这个声明:
xmlDoc.NameTable.Get("v")

我得到“v”,所以命名空间被定义了......对吗?

无论如何,为了让它起作用,我必须添加以下内容:
nsMan.AddNamespace("v", "urn:schemas-microsoft-com:vml");

为了让 XPath 查询工作(我检查过并且在源 xml 文档中定义了 v 命名空间),那么为什么这不能正常工作呢?

感谢您的帮助,

-nomad311

最佳答案

这是 XmlNode 对象如何工作以及访问 XML 文档中的命名空间的一个怪癖。

不幸的是,您必须使用 XmlNamespaceManager (正如您在问题中发布的代码中所做的那样)以便在您正在处理的 XML 文档中使用 namespace 。

来自 MSDN documentation for the .SelectNodes method of the XmlNode object :

XPath expressions can include namespaces. Namespace resolution is supported using the XmlNamespaceManager. If the XPath expression includes a prefix, the prefix and namespace URI pair must be added to the XmlNamespaceManager.

Note:

If the XPath expression does not include a prefix, it is assumed that the namespace URI is the empty namespace. If your XML includes a default namespace, you must still add a prefix and namespace URI to the XmlNamespaceManager; otherwise, you will not get any nodes selected. For more information, see Select Nodes Using XPath Navigation.



就其值(value)而言,使用 LINQ-To-XML 操作 XML 文档/节点要容易得多,也更“流畅”。

关于.Net 命名表(命名空间)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1510042/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com