You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.net中使用document.SelectNodes(XPath)时XmlNodeList返回0的问题

解决VB.NET XmlDocument.SelectNodes获取命名空间XML节点失败的问题

问题根源

你的XML文档中<definitions>节点使用了默认命名空间http://www.ABCdefg.com/XYZ,而XPath查询默认不会识别无前缀的命名空间节点,直接用definitions/types/*会匹配不到任何节点。另外代码还存在两处语法错误:

  • XmlDocument()声明多了括号,应改为New XmlDocument()
  • SelectNodes的字符串未闭合引号,且load方法首字母需大写为Load

解决方案

方法一:使用XmlNamespaceManager(推荐)

通过注册命名空间并在XPath中使用前缀精准匹配节点:

Dim doc As New XmlDocument()
doc.Load("XmlPath")
' 注册默认命名空间,前缀可自定义(这里用"ns")
Dim nsManager As New XmlNamespaceManager(doc.NameTable)
nsManager.AddNamespace("ns", "http://www.ABCdefg.com/XYZ")
' 使用带前缀的XPath查询type节点
Dim NodeList As XmlNodeList = doc.SelectNodes("ns:definitions/ns:types/ns:type", nsManager)

方法二:忽略命名空间查询(临时应急)

通过local-name()函数匹配节点本地名称,绕过命名空间限制(不推荐,易误匹配同名不同命名空间的节点):

Dim doc As New XmlDocument()
doc.Load("XmlPath")
Dim NodeList As XmlNodeList = doc.SelectNodes("//*[local-name()='definitions']/*[local-name()='types']/*[local-name()='type']")

验证

执行修正后的代码,NodeList.Count将返回正确的节点数量(示例XML中为1)。

内容的提问来源于stack exchange,提问作者Vivian Dsouza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 09:18:30