Alvin
Alvin

Reputation: 8499

LINQ to XML returns no result

I am using Linq to to parse an XML, but it return no result:

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.

Upvotes: 2

Views: 349

Answers (2)

Habib
Habib

Reputation: 223187

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.

 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

Upvotes: 1

abatishchev
abatishchev

Reputation: 100238

Your XML file contains namespaces thus you need to specify it when perform querying:

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

Upvotes: 7

Related Questions