Problems reading iTunes XML feed

I am trying to read an XML feed from http://itunes.apple.com/us/rss/topsongs/limit=10/genre=2/xml .

I want to access the following fields:

<im:price amount="1.29000" currency="USD">$1.29</im:price>
<im:releaseDate label="December 31, 1960">1960-12-31T16:00:00-07:00</im:releaseDate>

      

Here's what I've done so far:

var xml = "http://itunes.apple.com/us/rss/topsongs/limit=10/genre=2/xml";
XmlDocument doc = new XmlDocument();
doc.Load(xml);
XmlNodeList items = doc.SelectNodes("//entry");
foreach (var item in items) {
    // Do something with item.
}

      

Bad luck. items

is null. What for? What am I doing wrong?

+3


source to share


1 answer


You need to create a namespace manager to map the RSS as well as the proper namespaces of the iTunes tag names with short prefixes (itunes and im in the example below):

var xml = "http://itunes.apple.com/us/rss/topsongs/limit=10/genre=2/xml";

XmlDocument doc = new XmlDocument();
doc.Load(xml);
var namespaceManager = new XmlNamespaceManager(doc.NameTable);
namespaceManager.AddNamespace("itunes", "http://www.w3.org/2005/Atom");
namespaceManager.AddNamespace("im", "http://itunes.apple.com/rss");

XmlNodeList items = doc.SelectNodes("//itunes:entry", namespaceManager);
foreach (XmlNode item in items)
{
    var price = item.SelectSingleNode("im:price", namespaceManager);
    var releaseDate = item.SelectSingleNode("im:releaseDate", namespaceManager);

    if (price != null)
    {
        Console.WriteLine(price.Attributes["amount"].InnerText);
    }

    if (releaseDate != null)
    {
        Console.WriteLine(releaseDate.Attributes["label"].InnerText);
    }
}

      

For this particular feed, you should get 10 entries.

In the docs :

If the XPath expression does not contain a prefix, the namespace URI is assumed to be an empty namespace. If your XML contains a default namespace, you must still use the XmlNamespaceManager and add the namespace prefix and URI; otherwise, you will not receive any selected nodes. For more information, see Selecting Nodes Using XPath Navigation.



Alternatively, you can use the agthostic XPath namespace (from here ):

XmlNodeList items = doc.SelectNodes("//*[local-name() = 'entry']");

      

Finally, not sure why you said the elements are null. Can not be. When you run the source code, you should get the following:

enter image description here

+4


source







All Articles