如何在C#后端获取SOAP XML中username子节点的值?
解决C#中SOAP XML获取username节点值的问题
你的代码无法生效的核心原因是:username节点继承了父节点api:some_api_call的命名空间(http://127.0.0.1/Integrics/Enswitch/API),但你在XPath中没有为username指定对应的命名空间前缀,导致节点匹配失败。另外,代码中添加的encodingStyle命名空间完全多余,它是元素的属性,并非需要注册的命名空间前缀。
修正后的代码方案
方案一:规范指定命名空间前缀
直接在XPath中给username加上api前缀,因为它属于父节点的命名空间:
public static string SoapNodeValue(string xmlString) { XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(xmlString); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable); nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/"); nsmgr.AddNamespace("api", "http://127.0.0.1/Integrics/Enswitch/API"); // 只保留必要的命名空间,xsi、xsd和多余的encodingStyle可移除 XmlNode usernameNode = xdoc.SelectSingleNode("/soapenv:Envelope/soapenv:Body/api:some_api_call/api:username", nsmgr); return usernameNode?.InnerText ?? string.Empty; }
方案二:忽略命名空间匹配(适用于不确定命名空间的场景)
如果不想依赖命名空间,可以通过匹配节点本地名称的方式获取:
public static string SoapNodeValue(string xmlString) { XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(xmlString); // 使用local-name()忽略命名空间匹配 XmlNode usernameNode = xdoc.SelectSingleNode("//*[local-name()='username']"); return usernameNode?.InnerText ?? string.Empty; }
额外说明
- 优先使用方案一,SOAP XML的命名空间是规范的一部分,明确指定命名空间能避免因命名空间变化导致的匹配失败。
- 添加
?.InnerText ?? string.Empty是为了避免节点不存在时抛出空引用异常,增强代码健壮性。
内容的提问来源于stack exchange,提问作者Jessica
相关产品推荐
相关产品推荐

