2011-05-19 100 views
1

在訂閱源中無法獲得任何結果。 feedXML具有正確的數據。LINQ查詢問題

XDocument feedXML = XDocument.Load(@"http://search.twitter.com/search.atom?q=twitter"); 

var feeds = from entry in feedXML.Descendants("entry") 
      select new 
      { 
       PublicationDate = entry.Element("published").Value, 
       Title = entry.Element("title").Value 
      }; 

我錯過了什麼?

+0

你在飼料中得到什麼?你有沒有例外?您可以發佈一個xml的片段嗎? – 2011-05-19 12:45:06

+3

XML中是否有任何名稱空間? – 2011-05-19 12:46:13

回答

2

您需要在後代和元素方法中指定命名空間。

XDocument feedXML = XDocument.Load(@"http://search.twitter.com/search.atom?q=twitter"); 

XNamespace ns = "http://www.w3.org/2005/Atom"; 
var feeds = from entry in feedXML.Descendants(ns + "entry") 
      select new 
      { 
      PublicationDate = entry.Element(ns + "published").Value, 
      Title = entry.Element(ns + "title").Value 
      }; 
3

你需要指定命名空間:

// This is the default namespace within the feed, as specified 
// xmlns="..." 
XNamespace ns = "http://www.w3.org/2005/Atom"; 

var feeds = from entry in feedXML.Descendants(ns + "entry") 
      ... 

命名空間處理是在LINQ to XML精美容易一切其他XML API我用過:)

0

如果你看一下比較由HTTP請求返回的XML,您將看到它定義了一個XML名稱空間:

<?xml version="1.0" encoding="UTF-8"?> 
<feed xmlns="http://www.w3.org/2005/Atom" ...> 
    <id>tag:search.twitter.com,2005:search/twitter</id> 
    ... 
</feed> 

XML就像C#一樣,如果你使用具有錯誤名稱空間的元素名稱,它不被認爲是相同的元素!您需要將所需的namepsace添加到您的查詢中:

private static string AtomNamespace = "http://www.w3.org/2005/Atom"; 

public static XName Entry = XName.Get("entry", AtomNamespace); 

public static XName Published = XName.Get("published", AtomNamespace); 

public static XName Title = XName.Get("title", AtomNamespace); 

var items = doc.Descendants(AtomConst.Entry) 
       .Select(entryElement => new FeedItemViewModel() 
       new { 
        Title = entryElement.Descendants(AtomConst.Title).Single().Value, 
        ... 
       }); 
+0

任何不使這些只讀的原因,而不是使XNamespace類型的AtomNamespace? (我更喜歡+運營商來減少絨毛。) – 2011-05-19 12:55:24

0

問題出在feedXML.Descendants("entry")。這是返回0結果 根據the documentation您需要輸入一個完全合格的XName