简体   繁体   中英

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>

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM