使用LINQ to XML解析SOAP响应 - 如何在父级下获取嵌套节点?

Eva*_*van 7 c# linq asp.net 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>
Run Code Online (Sandbox Code Playgroud)

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

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();
Run Code Online (Sandbox Code Playgroud)

但是,调用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();
Run Code Online (Sandbox Code Playgroud)

所以,这告诉我的是在我原来的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();
Run Code Online (Sandbox Code Playgroud)

不是很好:)

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

Bro*_*ass 7

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

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