如果元素具有xmlns属性,则XDocument和Linq返回null

新手与XDocuments和Linq,请建议一个解决方案,从xml字符串中的特定标签检索数据:

如果我有来自webservice响应的XML字符串(为了方便我格式化了xml):

    Hello!    

使用以下代码,仅当GetCashFlowReportResponse标记没有"xmlns"属性时,才能获取该值。 不知道为什么? 否则,它始终返回null。

 string inputString = "Hello!" 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服务以删除该属性。 有没有更好的方法来读取响应并将实际数据返回给用户(以更易读的forms)?

编辑: 解决方案:

 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); } 

注意:即使所有子元素都没有namespace属性,如果向元素添加“ns”,代码也会起作用,因为我猜孩子们从父级inheritance命名空间(参见SLaks的响应)。

您需要包含命名空间:

 XNamespace ns = "http://tempuri.org/"; xDoc.Descendants(ns + "GetCashFlowReportResponse") 
 XName qualifiedName = XName.Get("GetCashFlowReportResponse", "http://tempuri.org/"); var data = from d in xDoc.Descendants(qualifiedName) 

只需使用限定名称来询问元素:

 // create a XML namespace object XNamespace ns = XNamespace.Get("http://tempuri.org/"); var data = from c in xDoc.Descendants(ns + "GetCashFlowReportResponse") select (string)c.Element(ns + "GetCashFlowReportPdf"); 

请注意使用重载+运算符创建带有XML命名空间和本地名称字符串的QName。