Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c# - No Nodes Selected from Atom XML document using XPath?

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.

I've been using this Atom feed as a test: http://steve-yegge.blogspot.com/feeds/posts/default

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);
}

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");

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?

EDIT

Although this question has an answer, I found out this question has an almost exact duplicate: SelectNodes not working on stackoverflow feed

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

And change your XPath appropriately:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...