如何从SOAP格式XML中提取并拆分<Person>节点内容?
解决SOAP XML解析:提取Person节点并转换为对象
第一步:排查XML语法错误
报错提示的行18位11位置,大概率存在未转义的<字符——比如XML文本内容里直接写了<30这种格式,而非转义后的<30;也可能是SOAP XML本身存在标签未闭合、属性值缺失引号等语法问题。先修正该位置的XML格式,确保语法合法。
第二步:正确解析SOAP XML(处理命名空间)
SOAP XML默认带命名空间,直接用XElement查找节点会匹配失败,必须指定对应命名空间。以下是完整解析示例:
1. 定义Person实体类
public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }
2. 解析SOAP XML并提取Person节点
假设你的SOAP XML结构如下:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetPersonsResponse xmlns="http://your-service-namespace.com/"> <GetPersonsResult> <Person> <Id>1</Id> <Name>张三</Name> <Age>28</Age> </Person> <Person> <Id>2</Id> <Name>李四</Name> <Age>32</Age> </Person> </GetPersonsResult> </GetPersonsResponse> </soap:Body> </soap:Envelope>
对应的解析代码:
// soapXml为你的SOAP XML字符串 XElement soapEnvelope = XElement.Parse(soapXml); // 声明SOAP和业务服务的命名空间 XNamespace soapNs = "http://schemas.xmlsoap.org/soap/envelope/"; XNamespace serviceNs = "http://your-service-namespace.com/"; // 逐层定位并提取所有Person节点 var personElements = soapEnvelope .Element(soapNs + "Body") .Element(serviceNs + "GetPersonsResponse") .Element(serviceNs + "GetPersonsResult") .Elements(serviceNs + "Person"); // 转换为Person对象列表 List<Person> persons = personElements.Select(p => new Person { Id = int.Parse(p.Element(serviceNs + "Id")?.Value ?? "0"), Name = p.Element(serviceNs + "Name")?.Value ?? string.Empty, Age = int.Parse(p.Element(serviceNs + "Age")?.Value ?? "0") }).ToList();
第三步:处理第三方返回的非法XML
如果是第三方接口返回的XML存在未转义的<,可先做简单预处理(仅针对文本中的非法<,避免破坏正常标签):
// 替换非标签内的<为转义字符 string cleanedXml = Regex.Replace(soapXml, @"(?<!<)(<)(?!/?[a-zA-Z0-9_]+>)", "<"); XElement soapEnvelope = XElement.Parse(cleanedXml);
常见避坑点
- 必须带命名空间查找节点,直接用
Element("Body")会匹配失败 - 解析子节点时要判断是否为null,避免空引用异常
- 优先确保XML语法合法,再进行节点提取和对象转换
内容的提问来源于stack exchange,提问作者Student
相关产品推荐
相关产品推荐

