簡體   English   中英

LINQ to XML沒有返回任何結果

[英]LINQ to XML returns no result

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

有沒有其他好的方法呢? 謝謝。

您的XML文件包含名稱空間,因此您需要在執行查詢時指定它:

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

因為您在查詢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