使用XPath从Atom XML文档中选择无节点?

时间:2009-02-01 17:13:00

标签: c# xml xpath xmldocument atom-feed

我正在尝试以编程方式解析Atom提要。我将原子XML下载为字符串。我可以将XML加载到XmlDocument中。但是,我无法使用XPath遍历文档。每当我尝试时,我都会得到null

我一直在使用此Atom Feed作为测试:http://steve-yegge.blogspot.com/feeds/posts/default

除了我使用“SelectSingleNode()”时,调用null始终会返回/。以下是我现在正在尝试的内容:

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,所以我也尝试了一个简单的根节点查询,因为我知道root应该可以工作:

// I've tried both with & without the nsMngr declared above
XmlNode node = atom.SelectSingleNode("/feed");

无论我做什么,似乎都无法选择任何东西。显然我错过了一些东西,我只是无法弄清楚是什么。为了使XPath在这个Atom提要上运行,我需要做些什么?

修改

  

虽然这个问题有答案,但我发现这个问题几乎完全重复:SelectNodes not working on stackoverflow feed

2 个答案:

答案 0 :(得分:8)

虽然C#实现可能允许默认命名空间(我不知道),但XPath 1.0规范却没有。所以,给“Atom”自己的前缀:

nsMngr.AddNamespace("atom", "http://www.w3.org/2005/Atom");

并适当更改XPath:

XmlNode node = atom.SelectSingleNode("//atom:entry/atom:link/app:edited", nsMngr);

答案 1 :(得分:0)

从字符串加载XML并查找任何“错误/错误”节点。

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlResult);            
XmlNamespaceManager nm = new XmlNamespaceManager(xmlDoc.NameTable);
nm.AddNamespace("ns", "http://somedomain.com/namespace1/2"); //ns - any name, make sure it is same in the below line

XmlNodeList errors = xmlDoc.SelectNodes("/ns:*//ns:Errors/ns:Error", nm);       

-Mathulan