2012-04-15 72 views
3

我想在C#中使用XPath獲取<鏈接>節點的href值YouTube most popular Atom feedXPath不返回結果 - YouTube feed

從我在網上閱讀文檔,這個過程會相對簡單,沿着線的東西:

XmlDocument xml = new XmlDocument(); 
xml.Load("http://gdata.youtube.com/feeds/api/standardfeeds/most_popular"); 
XmlNodeList linkNodes; 
linkNodes = xml.SelectNodes("/feed/entry/link[@rel='alternate']"); 

但是,這並不工作,我沒有得到任何結果。我試過用XmlNamespaceManager添加命名空間,但這也沒有幫助。

寒冷的答覆將不勝感激!謝謝!

回答

4

我確定正確添加命名空間會幫助,因爲我確定這是問題所在。就我個人而言,我會使用LINQ到XML。示例代碼:

using System; 
using System.Linq; 
using System.Xml.Linq; 

public class Test 
{ 
    static void Main() 
    { 
     string url = 
      "http://gdata.youtube.com/feeds/api/standardfeeds/most_popular"; 
     var doc = XDocument.Load(url); 
     XNamespace ns = "http://www.w3.org/2005/Atom"; 
     var links = doc.Root 
         .Elements(ns + "entry") 
         .Elements(ns + "link") 
         .Where(x => (string) x.Attribute("rel") == "alternate"); 

     Console.WriteLine(links.Count()); // 25 
    } 
} 
+0

非凡!謝謝,我會放棄它,並返回我的結果。 – 2012-04-15 21:25:29

+0

+1我今年的目標是實際使用System.Xml.Linq,感謝這個例子。 – dash 2012-04-15 21:41:12

+0

@dash:我發現現在使用任何其他XML API都很痛苦:) – 2012-04-15 21:42:11

3

喬恩的答案肯定是(今天去或隨時;-)的方式,但如果你有興趣,你在做什麼錯誤的話,這裏有一個例子:

命名空間呢存在於你的元素中,它是默認的命名空間。不幸的是,XmlDocument班在向你展示這件作品時並不那麼高雅。相反,您通常會在文檔中的根名稱空間上僞造名稱空間前綴映射;在這種情況下xmlns=http://www.w3.org/2005/Atom

XmlDocument xdoc = new XmlDocument(); 
    xdoc.Load("http://gdata.youtube.com/feeds/api/standardfeeds/most_popular"); 

    XmlNamespaceManager manager = new XmlNamespaceManager(xdoc.NameTable); 
    manager.AddNamespace("base", "http://www.w3.org/2005/Atom"); 

    var nodes = xdoc.SelectNodes("/base:feed/base:entry/base:link[@rel='alternate']", manager); 

測試你活的文件得到包含25種link元素的XmlNodeList中。

+0

謝謝,這非常有幫助。我確實沿着這些路線嘗試了一些東西,但我一定在某個地方搞砸了。 – 2012-04-15 21:47:08