使用 Xpath 从 XmlNode 获取元素
我正在尝试获取此 xml 提要中每个条目的标题和链接
I'm trying to get the title and link of each entry in this xml feed
https://www.businessopportunities.ukti.gov.uk/alertfeed/商业机会.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;
}
在 XPath 表达式中,前导 /
表示应该从 root 开始计算表达式文档的节点.这种表达式称为绝对路径表达式.你的第一个表情:
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
意思
从文档的根节点开始,然后寻找最外面的元素atom:entry
,然后选择其名为atom:title
的子元素.
Start at the root node of the document, then look for the outermost element
atom:entry
, then select its child elements calledatom:title
.
但很明显,atom:entry
不是文档的最外层元素.
But obviously, atom:entry
is not the outermost element of the document.
简单的改变
var title = entry.SelectSingleNode("/atom:entry/atom:title", nsm).InnerText;
var link = entry.SelectSingleNode("/atom:entry/atom:link", nsm).InnerText;
到
var title = entry.SelectSingleNode("atom:title", nsm).InnerText;
var link = entry.SelectSingleNode("atom:link", nsm).InnerText;