c# - 使用 LINQ to XML 解析 SOAP 响应 - 如何获取父项下的嵌套节点?

标签 c# asp.net linq soap linq-to-xml

我有一个类似于此的 SOAP 响应:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <getLoginResponse xmlns="http://<remotesite>/webservices">
        <person_id>123456</person_id>
        <person_name>John Doe</person_name>
    </getLoginResponse>
  </soapenv:Body>
</soapenv:Envelope>

我已经能够使用以下 LINQ 代码成功提取 <get LoginResponse ...> 节点:

string soapResult = rd.ReadToEnd();

XNamespace ns = "http://<remotesite>/webservices";

XDocument xDoc = XDocument.Parse(soapResult);

var respUser = (from r in xDoc.Descendants(ns + "getLoginResponse")
                select new User
                           {
                               Name = r.Element("person_name").Value
                           }).FirstOrDefault();

但是,对 Name = r.Element("person_name").Value 的调用给我一个 Object reference not set to an instance of an object 错误。

我进一步调查了这一点,发现如果我运行此查询,所有值(person_id、person_name)实际上都在嵌套 .Descendants().Descendants() XElement 集合中:

var respUser = (from r in xDoc.Descendants(ns + "getLoginResponse") 
                select r).Descendants().ToList();

所以,这告诉我的是在我原来的 LINQ 查询中,我没有正确提取 <getLoginResponse> 下的节点。

我如何将它们组合在一起,使用 ... select new User { ... } 来填充我的自定义对象?

做类似的事情:

var respUser = (from r in xDoc.Descendants(ns + "getLoginResponse").Descendants()
                select new User()
                              {
                                 Name = r.Element("person_name").Value
                              }).FirstOrDefault();

效果不是很好 :)

感谢大家提供的解决方案 - 我从子元素中省略了命名空间,这导致了我的问题!

最佳答案

您需要为查询添加一个有效的命名空间,在您的示例中为 "http://foobar/webservices",例如:

XElement xml = XElement.Load(@"testData.xml");
XNamespace foobar = "http://foobar/webservices";
string personId = xml.Descendants(foobar + "person_id").First().Value;

关于c# - 使用 LINQ to XML 解析 SOAP 响应 - 如何获取父项下的嵌套节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9181742/

相关文章:

C# 部分反序列化

c# - Linq to Entities 左连接返回 0 条记录

c# - MS Linq 文档中的 Northwnd 来自哪里?

javascript - 将数组从 Javascript 传递到 asp.net

c# - 使用 Entity Framework 添加多个对象时如何获取多个对象的标识?

c# - Enyim Memcached Client 不写/读数据

c# - XNA 基本画图程序

c# - NewtonSoft JSON 序列化器和 UTF8 支持

c# - 使用 varbinary 使用 FileUpload 将图像检索到数据库

c# - 在 Global.asax.cs 中注册类