Using Xpath to get Element from XmlNode

假如想象 提交于 2019-12-11 18:06:10

问题


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

回答1:


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;


来源:https://stackoverflow.com/questions/29413435/using-xpath-to-get-element-from-xmlnode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!