我正在使用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();
}
还有其他好办法吗?谢谢。
答案 0 :(得分:7)
您的XML文件包含名称空间,因此您需要在执行查询时指定它:
XNamespace xn = "http://webService";
doc.Descendants(xn + "downloadInfoReturn")
答案 1 :(得分: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