如果元素xmlns属性的XDocument和LINQ返回null [英] XDocument and Linq returns null if the element has xmlns attribute

查看:293
本文介绍了如果元素xmlns属性的XDocument和LINQ返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新手与XDocuments和LINQ,请提出一个解决方案,以从​​XML字符串特定标记检索数据:

Newbie with XDocuments and Linq, please suggest a solution to retrieve the data from a particular tag in the xml string:

如果我有一个从Web服务响应的XML字符串(我格式化为便于XML):<?/ p>

If I have a XML string from webservice response (I formatted xml for ease):

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetCashFlowReportResponse xmlns="http://tempuri.org/">
      <GetCashFlowReportPdf>Hello!</GetCashFlowReportPdf>
    </GetCashFlowReportResponse>
  </soap:Body>
</soap:Envelope>



使用下面的代码,我可以得到价值只有当 GetCashFlowReportResponse 标记没有的xmlns属性。不知道为什么?否则,它总是返回null

Using the following code, I can get the value only if GetCashFlowReportResponse tag doesn't have "xmlns" attribute. Not sure why? Otherwise, it always return null.

string inputString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><GetCashFlowReportResponse xmlns=\"http://tempuri.org/\"><GetCashFlowReportPdf>Hello!</GetCashFlowReportPdf></GetCashFlowReportResponse></soap:Body></soap:Envelope>"    
XDocument xDoc = XDocument.Parse(inputString);
//XNamespace ns = "http://tempuri.org/";
XNamespace ns = XNamespace.Get("http://tempuri.org/");

var data = from c in xDoc.Descendants(ns + "GetCashFlowReportResponse")
           select (string)c.Element("GetCashFlowReportPdf");

foreach (string val in data)
{
    Console.WriteLine(val);
}



我不能更改Web服务来删除属性。 ?有没有更好的方式来读取响应,并得到实际的数据传回给用户(更可读的形式)

I can't change the web service to remove that attribute. IS there a better way to read the response and get the actual data back to the user (in more readable form)?

编辑:
解决方案

XDocument xDoc = XDocument.Parse(inputString);
XNamespace ns = "http://tempuri.org/";

var data = from c in xDoc.Descendants(ns + "GetCashFlowReportResponse")
           select (string)c.Element(ns + "GetCashFlowReportPdf");
foreach (string val in data)
{
   Console.WriteLine(val);
}

请注意:即使所有的子元素没有命名空间属性,如果添加了NS为我猜孩子的继承父(请参阅从SLaks响应)命名空间中的元素的代码将工作。

Note: Even if all the child elements doesn't have the namespace attribute, the code will work if you add the "ns" to the element as I guess childs inherit the namespace from parent (see response from SLaks).

推荐答案

您需要包括命名空间:

XNamespace ns = "http://tempuri.org/";

xDoc.Descendants(ns + "GetCashFlowReportResponse")

这篇关于如果元素xmlns属性的XDocument和LINQ返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆