2

我正在使用 Linq 来解析 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();
}

有没有其他好的方法可以做到这一点?谢谢你。

4

2 回答 2

7

您的 XML 文件包含命名空间,因此您需要在执行查询时指定它:

XNamespace xn = "http://webService";
doc.Descendants(xn + "downloadInfoReturn")
于 2012-07-04T09:08:50.800 回答
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
于 2012-07-04T09:26:30.577 回答