加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:31:35 所属栏目:百科 来源:网络整理
导读:我正在尝试以编程方式解析Atom提要.我将原子 XML下载为字符串.我可以将 XML加载到XmlDocument中.但是,我无法使用XPath遍历文档.每当我尝试时,我都会失效. 我一直在使用这个Atom提要作为测试:http://steve-yegge.blogspot.com/feeds/posts/default 调用Selec
我正在尝试以编程方式解析Atom提要.我将原子 XML下载为字符串.我可以将 XML加载到XmlDocument中.但是,我无法使用XPath遍历文档.每当我尝试时,我都会失效.

我一直在使用这个Atom提要作为测试: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提要上工作,我需要做些什么?

编辑

Although this question has an answer,I found out this question has an almost exact duplicate: 07001

解决方法

虽然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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读