123456 John Doe 我已经能够使用以下 LINQ 代-6ren">
gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:17:55 35 4
gpt4 key购买 nike

我有一个类似于此的 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com