You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从SOAP格式XML中提取并拆分<Person>节点内容?

解决SOAP XML解析:提取Person节点并转换为对象

第一步:排查XML语法错误

报错提示的行18位11位置,大概率存在未转义的<字符——比如XML文本内容里直接写了<30这种格式,而非转义后的&lt;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_]+>)", "&lt;");
XElement soapEnvelope = XElement.Parse(cleanedXml);

常见避坑点

  • 必须带命名空间查找节点,直接用Element("Body")会匹配失败
  • 解析子节点时要判断是否为null,避免空引用异常
  • 优先确保XML语法合法,再进行节点提取和对象转换

内容的提问来源于stack exchange,提问作者Student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 08:30:05