首页 > 解决方案 > 使用 C# 从特定标记下的 SOAP 响应中检索数据列表

问题描述

我正在尝试将 SOAP 响应数据作为列表加载到 c# 模型对象中,以将其保存在数据库中。以下是我尝试过但无法访问数据的代码

using (WebResponse Serviceres = Request.GetResponse())
        {
            using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream()))
            {
                //reading stream  
                var ServiceResult = rd.ReadToEnd();
                var doc = XDocument.Parse(ServiceResult);
                
                //My though is to load the data in c# model object
                //Tried doc.Elements("Records") etc

下面是我从 SOAP 请求中得到的响应

<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>
  <soapenv:Header/>
  <soapenv:Body>
<QueryResult xmlns='http://www.niku.com/xog/Query' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
  <Code>cpcf_Project_Code</Code>
  <Records>
    <Record>
      <Id>5029026</Id>
      <Name>Admin</Name>
      <Code>1006</Code>
      <Status>Approved</Status>
      <IsActive>1</IsActive>
    </Record>
    <Record>
      <Id>50236</Id>
      <Name>USA</Name>
      <Code>10426</Code>
      <Status>Approved</Status>
      <IsActive>1</IsActive>
    </Record>
  </Records>
  <Slice>
    <Number>0</Number>
    <Size>7268</Size>
    <Total>7268</Total>
  </Slice>
</QueryResult>
  </soapenv:Body>
</soapenv:Envelope>

我想从你们那里得到帮助,用最好的方法来检索数据并将其保存在数据库中。您的意见在这个时候是最有价值的。谢谢。

标签: c#xmllinqsoap

解决方案


你可以这样做:

1 - 类

public class Record
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Code { get; set; }

    public string Status { get; set; }

    public bool IsActive { get; set; }
}

2 - 代码:

XDocument doc = XDocument.Parse(xml);
XNamespace xn = "http://www.niku.com/xog/Query";

List<Record> records = doc.Descendants(xn + "Record")
    .Select(x => new Record
    {
        Id = int.Parse(x.Element(xn + "Id").Value),
        Name = x.Element(xn + "Name").Value,
        Code = int.Parse(x.Element(xn + "Code").Value),
        Status = x.Element(xn + "Status").Value,
        IsActive = x.Element(xn + "IsActive").Value == "1",
    }).ToList();

请注意,我考虑了IsActivetake1或的值0

我希望你觉得这有帮助。


推荐阅读