2009-08-03 92 views
2

我試圖解析來自YouTube API的結果。我以字符串的形式正確地獲取結果,但無法正確解析它。使用LINQ to XML在多個命名空間中處理XML

我在前面的主題上遵循了建議,但沒有得到任何結果。

我的示例代碼:

string response = youtubeService.GetSearchResults(search.Term, "published", 1, 50); 
XDocument xDoc = XDocument.Parse(response, LoadOptions.SetLineInfo); 
var list = xDoc.Descendants("entry").ToList(); 
var entries = from entry in xDoc.Descendants("entry") 
       select new 
       { 
        Id = entry.Element("id").Value, 
        Categories = entry.Elements("category").Select(c => c.Value) 
        //Published = entry.Element("published").Value, 
        //Title = entry.Element("title").Value, 
        //AuthorName = entry.Element("author").Element("name").Value, 
        //Thumnail = entry.Element("media:group").Elements("media:thumnail").ToList().ElementAt(0) 
       }; 
foreach (var entry in entries) 
{ 
    // entry.Id and entry.Categories available here 
} 

的問題是,項目具有計數0即使的XDocument顯然具有有效值。

響應變量(示例XML)的值,可以在這裏看到:http://snipt.org/lWm

(FYI:YouTube的模式是列在這裏:http://code.google.com/apis/youtube/2.0/developers_guide_protocol_understanding_video_feeds.html

誰能告訴我,我做錯了什麼這裏?

+0

你的第一個問題是沒有發佈一個失敗的例子XML。由於你的第一個問題,我不知道你的第二個問題是什麼。 – 2009-08-03 22:17:28

+0

也許你的第二個問題是你沒有在foreach循環中設置斷點?你嘗試過了,還是依賴於調試器? – 2009-08-03 22:19:01

回答

7

所有的數據都在「http://www.w3.org/2005/Atom」命名空間中;你需要在整個使用:

XNamespace ns = XNamespace.Get("http://www.w3.org/2005/Atom"); 

...

from entry in xDoc.Descendants(ns + "entry") 
select new 
{ 
    Id = entry.Element(ns + "id").Value, 
    Categories = entry.Elements(ns + "category").Select(c => c.Value) 
    ... 
}; 

等(未經測試)

2

您需要設置的命名空間。

命名空間中
與XML創建的XName,一個的XName可以在命名空間中,或者它可以在沒有命名空間。
對於C#,在命名空間中創建XName的推薦方法是聲明XNamespace對象,然後使用加法運算符的覆蓋。

http://msdn.microsoft.com/en-us/library/system.xml.linq.xname.aspx

3

當你看到prefix:name,這意味着name在其前綴已被宣佈爲prefix的命名空間。如果您查看文檔的頂部,您會看到一個xmlns:media=somethingsomething是用於任何前綴爲media的名稱空間。

這意味着你需要爲每個命名空間創建的XNamespace需要引用:

XNamespace media = XNamespace.Get("http://search.yahoo.com/mrss/"); 

,然後用media在該命名空間的名字:

media + "group" 

中的命名空間這個文件是:

xmlns="http://www.w3.org/2005/Atom" 
xmlns:app="http://www.w3.org/2007/app" 
xmlns:media="http://search.yahoo.com/mrss/" 
xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" 
xmlns:gd="http://schemas.google.com/g/2005" 
xmlns:gml="http://www.opengis.net/gml" 
xmlns:yt="http://gdata.youtube.com/schemas/2007" 
xmlns:georss="http://www.georss.org/georss"