Search code examples
c#xmlxpathxmldocument

Getting all entry Elements within a Namespace from XML using XPath


I'm trying to get all the entry elements so I can display them, haven't done Xpath for a while but I thought it would be fairly simple heres what I have so far - rssNodes count is 0, what am I missing?

XmlDocument rssXmlDoc = new XmlDocument();
rssXmlDoc.Load("http://www.businessopportunities.ukti.gov.uk/alertfeed/1425362.rss");

var rssNodes = rssXmlDoc.SelectNodes("feed/entry");

The XML file has the following structure:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <!-- some other child elements -->
  <entry>
    <!-- child elements -->
  </entry>
  <entry>
    <!-- child elements -->
  </entry>
  <!-- more entry elements -->
  <!-- some other child elements -->
</feed>

Solution

  • You need to properly use namespaces:

    var nsm = new XmlNamespaceManager(rssXmlDoc.NameTable);
    nsm.AddNamespace("atom", "http://www.w3.org/2005/Atom");
    
    var entries = rssXmlDoc.SelectNodes("/atom:feed/atom:entry", nsm);