简体   繁体   中英

Using Xpath to get Element from XmlNode

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

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 called atom: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;

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