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

C#解析带命名空间XML失败:无法获取aa:ConfigurationID的值

解决XML命名空间查询报错问题

你的代码有两个关键问题导致报错:

  • XPath路径冗余:xmlDoc.DocumentElement已经指向根节点<SOAP-ENV:Envelope>,所以XPath开头不需要再写SOAP-ENV:Envelope/
  • 未传入命名空间管理器:调用SelectSingleNode时必须把配置好的nsmgr作为第二个参数传入,否则XPath无法识别前缀对应的命名空间

修正后的代码如下:

string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?><SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://www.w3.org/2003/05/soap-envelope""    xmlns:aa=""http://www.axis.com/vapix/ws/action1"">    <SOAP-ENV:Header></SOAP-ENV:Header>    <SOAP-ENV:Body>        <aa:AddActionConfigurationResponse>            <aa:ConfigurationID>4</aa:ConfigurationID>        </aa:AddActionConfigurationResponse>    </SOAP-ENV:Body></SOAP-ENV:Envelope>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("SOAP-ENV", "http://www.w3.org/2003/05/soap-envelope");
nsmgr.AddNamespace("aa", "http://www.axis.com/vapix/ws/action1");
// 修正XPath路径,并传入命名空间管理器
var node = xmlDoc.DocumentElement.SelectSingleNode("SOAP-ENV:Body/aa:AddActionConfigurationResponse/aa:ConfigurationID", nsmgr).InnerText;
Console.WriteLine(node);

运行这段代码就能正确输出4。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:06:40