简体   繁体   English

LINQ to XML没有返回任何结果

[英]LINQ to XML returns no result

I am using Linq to to parse an XML, but it return no result: 我使用Linq来解析XML,但它没有返回结果:

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>

Code: 码:

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

Is there any other good method to do it? 有没有其他好的方法呢? Thank you. 谢谢。

Your XML file contains namespaces thus you need to specify it when perform querying: 您的XML文件包含名称空间,因此您需要在执行查询时指定它:

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

Because you are missing the namespace while querying the xml, also your class name doesn't match, try the following code, it works on my side. 因为您在查询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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM