c# - 使用 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>
我想从你们那里得到帮助,用最好的方法来检索数据并将其保存在数据库中。您的意见在这个时候是最有价值的。谢谢。
解决方案
你可以这样做:
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();
请注意,我考虑了IsActive
take1
或的值0
。
我希望你觉得这有帮助。
推荐阅读
- php - 上传文件php时返回false
- mysql - 使用日期和状态字段的mysql订购问题
- android - 可以在样式中完全限定可声明样式的属性(以避免命名冲突)吗?
- sql-server - 带有 CASE & NOT IN 条件的 SQL Where 子句
- django - Django 验证包含在基本模板中的(通讯)表单
- python - 生成给定点 10 公里内的纬度/经度列表
- javascript - 具有_任何可能的属性_的无限深度对象定义为既是又返回另一个无限深度对象的函数。JS
- javascript - 计算传感器未确定长度的运行平均值
- r - 使用 RAdwords 库连接并使用 doAuth 会出错
- opencv - 尝试使用 cmake-gui 构建“opencv_contrib”时出错