Link to home
Start Free TrialLog in
Avatar of joshuadavidlee
joshuadavidlee

asked on

System.Xml.XmlNodeList not working

Ok view the source of the following xml, its very simple layout:

http://news.google.com/news?ned=us&topic=h&output=atom

here is my code that works fine:

            System.Net.WebRequest myRequest = System.Net.WebRequest.Create(rssURL);      
            System.Net.WebResponse myResponse = myRequest.GetResponse();
         
            System.IO.Stream rssStream = myResponse.GetResponseStream();
            System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument();

            rssDoc.Load(rssStream);

here is the next line of code that is the problem:

System.Xml.XmlNodeList myXmlNodeList = rssDoc.SelectNodes("feed/entry");

it keeps coming back empty even though you can clearly see "feed" as the first node and plenty of child nodes called "entry".  
Please help.......



ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of joshuadavidlee
joshuadavidlee

ASKER

ok now that worked but i have a question, i have seen examples where the "entry" will also have a namespace for each "entry"  will this cause a problem also if I come across a feed that does this?
http://www.atomenabled.org/atom.xml  is an example where each "entry" has a namespace fro soem reason
That shouldn't be a problem because, if you notice, they all have the same namespace. They all just have the namespace explicitly stated because of the way it will have been put together. As long as the namespace is the same the previous code will work fine.

If for some reason they do have a different namespace then you can change your code to grab all nodes irrespective of the namespace using:

    System.Xml.XmlNodeList myXmlNodeList = rssDoc.SelectNodes("*[local-name()='feed']/*[local-name()='entry']");

But if the namespace doesn't change then the first code sample will be faster, you should only use this second method as a last resort.
ok thank you, could u explain why i even have to add the namespace myself ? since it is in the document when i load it anyways? i will be giving u the points btw
You're not actually adding a namespace, you are specifying an alias that refers to nodes belonging to the namespace. So, in the sample:

    ns.AddNamespace("x", "http://purl.org/atom/ns#");

You are saying that you will identify any nodes in the "http://purl.org/atom/ns#" namespace with the prefix "x". In XPath you have to use a prefix to refer to any nodes belonging to a namespace, even if it is the default namespace.
thanks you