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
相关产品推荐
相关产品推荐

