使用 Xpath 从 XmlNode 获取元素 [英] Using Xpath to get Element from XmlNode

查看:31
本文介绍了使用 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 called atom: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;

这篇关于使用 Xpath 从 XmlNode 获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆