Reputation: 2425
I'm trying to get the title and link of each entry in this xml feed
https://www.businessopportunities.ukti.gov.uk/alertfeed/businessopportunities.rss
Setting a breakpoint I can see that I am getting all the entries but I am getting an error when I try and get the title or link from the entry
XmlDocument rssXmlDoc = new XmlDocument();
rssXmlDoc.Load("https://www.businessopportunities.ukti.gov.uk/alertfeed/businessopportunities.rss");
var nsm = new XmlNamespaceManager(rssXmlDoc.NameTable);
nsm.AddNamespace("atom", "http://www.w3.org/2005/Atom");
XmlNodeList entries = rssXmlDoc.SelectNodes("/atom:feed/atom:entry", nsm);
foreach (XmlNode entry in entries)
{
var title = entry.SelectSingleNode("/atom:entry/atom:title", nsm).InnerText;
var link = entry.SelectSingleNode("/atom:entry/atom:link", nsm).InnerText;
}
Upvotes: 0
Views: 964
Reputation: 22647
In an XPath expression, a leading /
indicates that the expression should be evaluated starting from the root node of the document. This kind of expression is called an absolute path expression. Your first expression:
/atom:feed/atom:entry
really should be evaluated starting from the root, but all subsequent expressions should not. An expression like
/atom:entry/atom:title
means
Start at the root node of the document, then look for the outermost element
atom:entry
, then select its child elements calledatom:title
.
But obviously, atom:entry
is not the outermost element of the document.
Simply change
var title = entry.SelectSingleNode("/atom:entry/atom:title", nsm).InnerText;
var link = entry.SelectSingleNode("/atom:entry/atom:link", nsm).InnerText;
to
var title = entry.SelectSingleNode("atom:title", nsm).InnerText;
var link = entry.SelectSingleNode("atom:link", nsm).InnerText;
Upvotes: 1