Ayo Adesina
Ayo Adesina

Reputation: 2395

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>

Upvotes: 0

Views: 492

Answers (2)

helb
helb

Reputation: 7773

You need to respect XML namespaces with XPath.

NOTE: If the namespace of the entry element is known, see JLRishe's answer which is more elegant in that case.

If you don't know the XML namespace beforehand you can also ignore it using the XPath built-in local-name() function:

SelectNodes("//*[local-name()='entry']") 

This will get all entry elements in the entire XML document, no matter which namespace the element belongs to.

Upvotes: 0

JLRishe
JLRishe

Reputation: 101680

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

Upvotes: 3

Related Questions