LINQ to XML没有返回任何结果

Alv*_*vin 2 .net c# xml linq linq-to-xml

我使用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>
Run Code Online (Sandbox Code Playgroud)

码:

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();
}
Run Code Online (Sandbox Code Playgroud)

有没有其他好的方法呢?谢谢.

aba*_*hev 7

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

XNamespace xn = "http://webService";
doc.Descendants(xn + "downloadInfoReturn")
Run Code Online (Sandbox Code Playgroud)