没有使用XPath从Atom XML文档中选择节点? [英] No Nodes Selected from Atom XML document using XPath?
问题描述
我正在尝试以编程方式解析Atom供稿。我将原子XML下载为字符串。我可以将XML加载到 XmlDocument
中。但是,我无法使用XPath遍历文档。每当我尝试时,都会得到 null
。
I'm trying to parse an Atom feed programmatically. I have the atom XML downloaded as a string. I can load the XML into an XmlDocument
. However, I can't traverse the document using XPath. Whenever I try, I get null
.
我一直在使用此Atom提要作为测试: http://steve-yegge.blogspot.com/feeds/posts/default
I've been using this Atom feed as a test: http://steve-yegge.blogspot.com/feeds/posts/default
调用 SelectSingleNode()
始终返回 null
,当我使用 /
时。这是我现在正在尝试的方法:
Calling SelectSingleNode()
always returns null
, except for when I use "/
". Here is what I'm trying right now:
using (WebClient wc = new WebClient())
{
string xml = wc.DownloadString("http://steve-yegge.blogspot.com/feeds/posts/default");
XmlNamespaceManager nsMngr = new XmlNamespaceManager(new NameTable());
nsMngr.AddNamespace(string.Empty, "http://www.w3.org/2005/Atom");
nsMngr.AddNamespace("app", "http://purl.org/atom/app#");
XmlDocument atom = new XmlDocument();
atom.LoadXml(xml);
XmlNode node = atom.SelectSingleNode("//entry/link/app:edited", nsMngr);
}
我认为可能是因为我的XPath,所以我也因为我知道根节点应该工作,所以尝试了一个简单的根节点查询:
I thought it might have been because of my XPath, so I've also tried a simple query of the root node since I knew the root should work:
// I've tried both with & without the nsMngr declared above
XmlNode node = atom.SelectSingleNode("/feed");
无论我做什么,似乎都无法选择。显然我遗漏了一些东西,只是无法弄清楚是什么。为了使XPath可以在此Atom订阅源上工作,我需要做什么?
No matter what I do, it seems like it can't select anything. Obviously I'm missing something, I just can't figure out what. What is it that I need to do in order to make XPath work on this Atom feed?
尽管这个问题有答案,但我发现这个问题几乎是重复的: SelectNodes无法使用stackoverflow feed
推荐答案
C#实现可能允许使用默认名称空间(我不知道),而XPath 1.0规范则不允许。因此,给 Atom加上自己的前缀:
While the C# implementation may allow default namespaces (I don't know), the XPath 1.0 spec doesn't. So, give "Atom" its own prefix:
nsMngr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
然后适当地更改XPath:
And change your XPath appropriately:
XmlNode node = atom.SelectSingleNode("//atom:entry/atom:link/app:edited", nsMngr);
这篇关于没有使用XPath从Atom XML文档中选择节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!