2013-02-19 79 views
1

的默認命名空間,我叫幾個類中的方法是這樣的:的LINQ to XML:得到RSS

GetResult(XElement item, XNamespace ns) { 
    item.Element(ns + "title").Value; 
} 

爲了初始化飼料和訪問元素表示上面我想找出默認命名空間。如果沒有任何名稱空間聲明,它會正常工作(item.Element(「title」).value),並返回元素的值。

那麼如何找到正確的命名空間?該方法root.GetDefaultNamespace()的結果爲空莫名其妙...

<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0"> 
    <channel>...</channel> 
</rss> 

//編輯

好了,到目前爲止我的代碼:

XDocument thisFeed = XDocument.Load(@"http://www.spiegel.de/schlagzeilen/tops/index.rss"); 
    XElement root = thisFeed.Root; 
    XNamespace ns = root.GetNamespaceOfPrefix("content"); 
    //result: 
    Console.WriteLine("DefaultNamespace: " + root.GetDefaultNamespace()); 
    //result: http://purl.org/rss/1.0/modules/content/ 
    Console.WriteLine("GetNamespaceOfPrefix('content'): " + ns); 
    //works 
    Console.WriteLine("Result: " + root.Element("channel").Element("title").Value); 
    //Doesn't work 
    Console.WriteLine("Result: " + root.Element(ns + "channel").Element(ns + "title").Value); 
+0

似乎是你的rss「錯誤」,因爲確實沒有指定默認命名空間,只有一個「content」命名空間。也許你需要對它進行硬編碼? – Davio 2013-02-19 12:16:56

+0

可能不完全是你要求的,但你有沒有嘗試過SyndicationFeed類(http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx)?我發現它非常有用。 – bytefire 2013-02-19 12:28:39

回答

0

試試這樣說:

XNamespace ns = doc.Root.GetNamespaceOfPrefix("content"); 

你的樣品中content前綴。命名空間和前綴的尼斯解釋可以在這個w3schools article

更新中找到:

有該文件中沒有定義默認的命名空間,只有一個前綴元素的命名空間,其他元素不檢索命名空間。我發現只有元素<content:encoded>要使用前綴,因此您需要使用ns

+0

感謝您的回覆,但這似乎沒有奏效。 – Thrukal 2013-02-19 12:41:21

+0

不客氣。我使用您發佈的示例對其進行了測試,「GetNamespaceOfPrefix」方法返回'http://purl.org/rss/1.0/modules/content/'作爲名稱空間。當你運行這個時,你會得到什麼? (不是'GetDefaultNamespace' - 如果它被定義爲'xmlns =「http://purl.org/rss/1.0/modules/content/」'',則會返回名稱空間)。 rss'元素真的是根? – 2013-02-19 12:49:11

+0

爲了測試我使用這個飼料:http://www.spiegel.de/schlagzeilen/tops/index.rss請看我的第一篇文章的進一步細節。似乎很奇怪,默認的命名空間是空的... – Thrukal 2013-02-19 12:53:38