簡體   English   中英

C#Linq to XML無法使用

[英]C# Linq to XML not working with

string url = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=fosil+fuel";
List<Resource> sites = new List<Resource>();
WebRequest request = WebRequest.Create(url);
using (WebResponse response = request.GetResponse())
{
      // Get the response stream  
      StreamReader reader = new StreamReader(response.GetResponseStream());
      XDocument xmlDoc = new XDocument();
      xmlDoc = XDocument.Parse(reader.ReadToEnd());
      var results = from q in xmlDoc.Descendants("Result")
                    select new
                    {
                          Url = q.Element("ClickUrl").Value,
                          Title = q.Element("Title").Value,
                           Date = q.Element("ModificationDate").Value,
                     };
       foreach (var item in results)
       {
             sites.Add(new Resource(item.Title, item.Date, item.Url));
       }
}

yahoo xml如下所示:

<ResultSet xsi:schemaLocation="urn:yahoo:srch http://api.search.yahoo.com/WebSearchService/V1/WebSearchResponse.xsd" type="web" totalResultsAvailable="134000" totalResultsReturned="10" firstResultPosition="1" moreSearch="/WebSearchService/V1/webSearch?query=fosil+fuel&appid=YahooDemo&region=us">
    <Result>
        <Title>Fosil Fuel | Flickr - Photo Sharing!</Title>
        <Summary>Fosil Fuel ... &lt;a href="http://www.flickr.com/photos/thomashawk/3910488337/" title="Fosil Fuel by Thomas Hawk, on Flickr"&gt;&lt;img src="http://farm3.static.flickr. ...</Summary>
        <Url>http://www.flickr.com/photos/thomashawk/3910488337/</Url>
        <ClickUrl>http://www.flickr.com/photos/thomashawk/3910488337/</ClickUrl>
        <DisplayUrl>www.flickr.com/photos/thomashawk/3910488337/</DisplayUrl>
        <ModificationDate>1298707200</ModificationDate>
        <MimeType>text/html</MimeType>
        <Cache>
            <Url>http://uk.wrs.yahoo.com/_ylt=A0WTeekRk5dNbBEAx4zdmMwF;_ylu=X3oDMTBwZTdwbWtkBGNvbG8DZQRwb3MDMQRzZWMDc3IEdnRpZAM-/SIG=16k5dp83c/EXP=1301865617/**http%3A//66.218.69.11/search/cache%3Fei=UTF-8%26appid=YahooDemo%26query=fosil%2Bfuel%26u=www.flickr.com/photos/thomashawk/3910488337/%26w=fosil%2Bfuel%2Bfuels%26d=V6aQZ_bJWYzN%26icp=1%26.intl=us</Url>
            <Size>119332</Size>
            </Cache>
        </Result>
    </ResultSet>

我究竟做錯了什么? 每當我嘗試新的東西時,調試器都會提示我的結果是空的。

您需要指定一個名稱空間:xmlDoc.Descendants(XName.Get(“ Result”,“ urn:yahoo:srch”))

您可以稍微簡化一下代碼:

        var url = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=fosil+fuel";
        var request = WebRequest.Create(url);
        using (var response = request.GetResponse())
        {
            // Get the response stream  
            var xmlDoc = XDocument.Load(response.GetResponseStream());
            var results = from q in xmlDoc.Descendants(XName.Get("Result", "urn:yahoo:srch"))
                          select new Resource(
                              q.Element(XName.Get("Title", "urn:yahoo:srch").Value,
                              q.Element(XName.Get("ModificationDate", "urn:yahoo:srch").Value,
                              q.Element(XName.Get("ClickUrl", "urn:yahoo:srch").Value);
            return results.ToList();
        }

問題是“結果”具有您要忽略的名稱空間“ urn:yahoo:srch”。 試試xmlDoc.Descendants(XName.Get("Result", "urn:yahoo:srch")) ,它將起作用

假設您不需要為WebRequest設置代理或憑據,則可以比Talljoe實際提到的進一步簡化:

string url = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=fosil+fuel";
Func<string, XName> qualifiedName = name => XName.Get(name, "urn:yahoo:srch");
XDocument xmlDoc = XDocument.Load(url);
var results = from q in xmlDoc.Descendants(qualifiedName("Result")) 
              select new Resource(
                  q.Element(qualifiedName("ClickUrl")).Value, 
                  q.Element(qualifiedName("Title")).Value, 
                  q.Element(qualifiedName("ModificationDate")).Value); 
return results.ToList();

編輯-修復了我的原始響應中的錯誤(缺少XName用於訪問元素),並添加了一個時髦的Func<>以重用命名空間限定。 可在我的機器上運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM