2014-11-09 144 views
0

我試圖解析C#中的iTunes podcast XML feed並遇到了麻煩。它成功下載提要並將其放入XmlDocument對象(已測試)。之後,它會進入for-each行,但不會進入循環。我不知道爲什麼它說頻道/項目中沒有任何元素(至少這是我現在所想的)。繼承人代碼:在C#中使用System.Xml解析iTunes Podcast XML

string _returnedXMLData; 
    XmlDocument _podcastXmlData = new XmlDocument(); 

    public List<PodcastItem> PodcastItemsList = new List<PodcastItem>(); 

    _podcastXmlData.Load(@"http://thepointjax.com/Podcast/podcast.xml"); 

    string title = string.Empty; 
    string subtitle = string.Empty; 
    string author = string.Empty; 

    foreach (XmlNode node in _podcastXmlData.SelectNodes(@"channel/item")) { 
     title = node.SelectSingleNode (@"title").InnerText; 
     subtitle = node.SelectSingleNode (@"itunes:subtitle").InnerText; 
     author = node.SelectSingleNode (@"itunes:author").InnerText; 
     PodcastItemsList.Add (new PodcastItem(title, subtitle, author)); 
    } 
} 

預先感謝您的幫助!非常感謝!

柯克蘭

+0

任何你不能在這裏使用LINQ的理由? – Jonesopolis 2014-11-09 03:16:21

回答

1

去了我的評論,我只是用XDocument

var xml = XDocument.Load("http://thepointjax.com/Podcast/podcast.xml"); 

XNamespace ns = "http://www.itunes.com/dtds/podcast-1.0.dtd"; 
foreach (var item in xml.Descendants("item")) 
{ 
    var title = item.Element("title").Value; 
    var subtitle = item.Element(ns + "subtitle").Value; 
    var author = item.Element(ns + "author").Value; 

    PodcastItemsList.Add (new PodcastItem(title, subtitle, author)); 
} 

itunes是在XML命名空間,所以你需要使用一個XNamespace考慮到它。

+0

工作就像一個魅力!非常感謝你! – Kirkland 2014-11-09 17:36:37

+0

這個方法比我嘗試的那個方法還有什麼其他好處嗎?你認爲這是在大多數情況下解析XML的最佳方式嗎?你什麼時候使用這個呢?我很抱歉,我知道我聽起來像一個問卷,但我真的很想學習。任何迴應將不勝感激! – Kirkland 2014-11-09 17:38:45

+1

喬恩Skeet給了[更好的答案](http://stackoverflow.com/questions/1542073/xdocument-or-xmldocument),這比我將能夠提供給你。 – Jonesopolis 2014-11-09 18:21:45

0

僅供參考Apple的網站上說itunes命名空間鏈接區分大小寫。我還沒有使用version =「2.0」部分,但到目前爲止,我並不需要它。我正在使用我從其他地方複製的鏈接「... DTD/Podcast-1.0.dtd」。只有將它更改爲小寫後,我的RSS閱讀器中的解析才能開始工作。

Screenshot of Apple documentation