XmlNodeList SelectNodes trouble

1.4k views Asked by At

I'm trying to parse an xml file

My code looks like:

 string path2 = "xmlFile.xml";
 XmlDocument xDoc = new XmlDocument();
 xDoc.Load(path2);
 XmlNodeList xnList = xDoc.DocumentElement["feed"].SelectNodes("entry");

But can't seem to get the listing of nodes. I get the error message- "Use the 'new' keyword to create an object instance." and it seems to be on 'SelectNodes("entry")' This code worked when I loaded the xml from an rss feed, but not a local file. Can you tell me what I'm doing wrong?

My xml looks like:

<?xml version="1.0"?>
 <feed xmlns:media="http://search.yahoo.com/mrss/" xmlns:gr="http://www.google.com/schemas/reader/atom/" xmlns:idx="urn:atom-extension:indexing" xmlns="http://www.w3.org/2005/Atom" idx:index="no" gr:dir="ltr">
  <entry gr:crawl-timestamp-msec="1318667375230">
   <title type="html">Title 1 text</title>
   <summary>summary 1 text text text</summary>
  </entry>
  <entry gr:crawl-timestamp-msec="1318667375230">
   <title type="html">title 2 text</title>
   <summary>summary 2 text text text</summary>
  </entry>
 </feed>
2

There are 2 answers

1
Martin Honnen On BEST ANSWER

Take the namespace into acount:

XmlNamespaceManager mgr = new XmlNamespaceManager(XDoc.NameTable);
mgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
XmlNodeList xnList = xDoc.SelectNodes("//atom:entry", mgr);
0
Dimitre Novatchev On

This is the infamous most FAQ about XPath -- referring to the names of elements that are in a default namespace.

Short answer: search for "XPath default namespace" and understand the problem.

Then use an XmlNamespaceManager instance to add an association between a prefix (say "x") and the default namespace (in your case "http://www.w3.org/2005/Atom").

Finally, replace any Name with x:Name in your XPath expression.