Question

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>
Was it helpful?

Solution

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);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top