如何遍历字符串格式XML,读取Parameter节点的Key与Value值?
这问题挺典型的,尤其是带命名空间的XML,很多人会因为忽略命名空间导致找不到节点。我给你几个常用语言的实现方案,完全适配你提供的XML结构:
方案1:Python(使用内置的xml.etree.ElementTree)
Python的内置库就可以搞定,核心是要先注册XML里的命名空间,然后用XPath定位节点:
import xml.etree.ElementTree as ET # 你的XML字符串(替换成实际完整内容即可) xml_str = """<GetModuleInfoResult xmlns="http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Results" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Code>0</Code> <Message i:nil="true"/> <Parameters xmlns:a="http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities"> <a:Parameter> <a:Key>width</a:Key> <a:Value>1068</a:Value> </a:Parameter> <a:Parameter> <a:Key>height</a:Key> <a:Value>600</a:Value> </a:Parameter> </Parameters> </GetModuleInfoResult>""" # 解析XML字符串 root = ET.fromstring(xml_str) # 注册命名空间:给a前缀绑定对应的URL(必须和XML里的xmlns:a完全一致) ET.register_namespace('a', 'http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities') # 用XPath查找所有a:Parameter节点 parameters = root.findall('.//a:Parameter', namespaces={'a': 'http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities'}) # 遍历每个节点,提取Key和Value for param in parameters: key = param.find('a:Key', namespaces={'a': 'http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities'}).text value = param.find('a:Value', namespaces={'a': 'http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities'}).text print(f"Key: {key}, Value: {value}")
关键点:XML里的a:不是普通前缀,它绑定了一个固定的命名空间URL,必须在查找时明确指定,否则ElementTree会找不到这些节点。
方案2:C#(使用LINQ to XML)
如果是在.NET环境下,用LINQ to XML会更简洁,同样要处理命名空间:
using System; using System.Linq; using System.Xml.Linq; class Program { static void Main() { // 你的XML字符串 string xmlStr = @"<GetModuleInfoResult xmlns=""http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Results"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""> <Code>0</Code> <Message i:nil=""true""/> <Parameters xmlns:a=""http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities""> <a:Parameter> <a:Key>width</a:Key> <a:Value>1068</a:Value> </a:Parameter> <a:Parameter> <a:Key>height</a:Key> <a:Value>600</a:Value> </a:Parameter> </Parameters> </GetModuleInfoResult>"; // 加载XML文档 XDocument doc = XDocument.Parse(xmlStr); // 定义命名空间:对应XML里的xmlns:a XNamespace aNs = "http://schemas.datacontract.org/2004/07/GMS.Integration.Service.Contracts.Entities"; // 查找所有a:Parameter节点,提取Key和Value var parameters = doc.Descendants(aNs + "Parameter") .Select(p => new { Key = p.Element(aNs + "Key").Value, Value = p.Element(aNs + "Value").Value }); // 输出结果 foreach (var param in parameters) { Console.WriteLine($"Key: {param.Key}, Value: {param.Value}"); } } }
关键点:LINQ to XML中,命名空间和元素名是组合使用的,必须用aNs + "Parameter"来定位节点,不能直接写a:Parameter。
如果你用的是其他语言(比如Java、JavaScript),可以告诉我,我再补充对应的方案~
内容的提问来源于stack exchange,提问作者dan mann
相关产品推荐
相关产品推荐

