如何将C# XmlDocument中的ID值提取为List/Array?
正确提取SOAP响应中带命名空间的重复ID节点值
你的问题核心是没有正确处理XML命名空间,导致无法准确定位到重复的ID节点。以下是两种可行的解决方案:
方法一:使用LINQ to XML(XElement)
通过定义并指定命名空间,逐层定位到目标节点,提取所有ID值:
// 定义XML命名空间 XNamespace soapNs = "http://schemas.xmlsoap.org/soap/envelope/"; XNamespace evlogNs = "http://www.svt.si/evlog"; // 解析SOAP响应内容 XElement soapEnvelope = XElement.Parse(soapResponse); // 提取所有ID值到数组 string[] idArray = soapEnvelope .Element(soapNs + "Body") // 定位soap命名空间下的Body节点 .Element("InfoResponse") // InfoResponse无命名空间,直接使用节点名 .Elements(evlogNs + "ID") // 筛选evlog命名空间下的所有ID节点 .Select(idNode => idNode.Value) .ToArray(); // 遍历处理每个ID foreach (string id in idArray) { Logger.LogInfo("ID: " + id); }
方法二:使用XmlDocument
借助XmlNamespaceManager管理命名空间,通过XPath查询目标节点:
XmlDocument doc = new XmlDocument(); doc.LoadXml(soapResponse); // 创建命名空间管理器,注册所需命名空间前缀 XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable); nsMgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); nsMgr.AddNamespace("ns1", "http://www.svt.si/evlog"); // 用XPath查询所有ID节点 XmlNodeList idNodes = doc.SelectNodes("//soap:Body/InfoResponse/ns1:ID", nsMgr); // 转换为列表并处理 List<string> idList = new List<string>(); foreach (XmlNode node in idNodes) { string id = node.InnerText; idList.Add(id); Logger.LogInfo("ID: " + id); }
关键说明
- 之前的代码返回空数组,是因为
Descendants("InfoResponse")没有考虑到它嵌套在soap命名空间的Body节点内,直接搜索无命名空间节点会失败。 - 带前缀的节点(如
ns1:ID)必须通过对应命名空间定位,不能直接用"ID"作为节点名查询。
内容的提问来源于stack exchange,提问作者user805528
相关产品推荐
相关产品推荐

