2012-07-04 56 views
2

我使用LINQ到解析XML,但它不返回任何结果:的LINQ to XML返回任何结果

XML:

<?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> 
      <downloadInfoResponse xmlns="http://webService"> 
       <downloadInfoReturn> 
       <city>city</city> 
       <companyName>company name</companyName> 
      </downloadInfoReturn> 
     </downloadInfoResponse> 
    </soapenv:Body> 
</soapenv:Envelope> 

代码:

public class Merc 
{ 
    public string CompanyName { get; set; } 
} 

using (XmlReader reader = XmlReader.Create(new StringReader(result))) 
{ 
    XDocument doc = XDocument.Load(reader, LoadOptions.SetLineInfo); 
    List<Merc> m = (from downloadInfoReturn in doc.Descendants("downloadInfoReturn") 
        select new Merc 
        { 
         CompanyName = downloadMerchantInfoReturn.Element("companyName").Value 
        }).ToList(); 
} 

有什么其他好方法呢?谢谢。

+2

注意:你正在做'新商人',但你的班级名为'Merc'。如果问题能够真正运行,可以更容易地找到并测试问题。 –

回答

7

你的XML文件中包含的命名空间。因此,你需要执行查询时,将其指定:

XNamespace xn = "http://webService"; 
doc.Descendants(xn + "downloadInfoReturn") 
+0

谢谢。有一个新的错误:对象引用未设置为对象的实例。 – Alvin

+0

@KelvinFixx:你在哪一行得到它? – abatishchev

+0

在catch语句中。 – Alvin

1

因为你缺少的命名空间,而查询的XML,也是你的类名不符,请尝试以下代码,它在我身边运作。

List<Merc> m = null; 
XNamespace ns = "http://webService"; 
using (XmlReader reader = XmlReader.Create(new StringReader(result))) 
     { 
     XDocument doc = XDocument.Load(reader, LoadOptions.SetLineInfo); 
     m = (from downloadInfoReturn in doc.Descendants(ns + "downloadInfoReturn") 
        select new Merc 
         { 
         CompanyName = downloadInfoReturn.Element(ns+ "companyName").Value 
         }).ToList<Merc>(); 
      } 
    Console.WriteLine(m.Count); // this will show 1 
+0

我低估了,因为没有解释这实际上做了什么。伊万在另一个问题上也是如此。 – Tharwen

+0

他确实给了我一个线索来回答我的问题。谢谢哈比。 – Alvin

+0

@Habib这是正确的,我相信它有帮助,但是你不会在任何地方说出你的改变。 – Tharwen