开发者

What's wrong with this XPath query?

I'm trying to select nodes from an rss feed. It works fine for Twitter, but I can't do it on Youtube.

        string youtube = "http://gdata.youtube.com/feeds/api/users/CTVOlympics/uploads";
        string twitter = "http://twitter.com/statuses/user_timeline/ctvolympics.rss";

        //this populates the XmlNodeList object
        XmlTextReader readerTwitter = new XmlTextReader(twitter);
        XmlDocument docTwitter = new XmlDocument();
        docTwitter.Load(readerTwitter)开发者_如何转开发;
        XmlNodeList nodesTwitter = docTwitter.SelectNodes("/rss/channel/item");

        //this doesn't populate the object
        XmlTextReader readerYoutube = new XmlTextReader(youtube);
        XmlDocument docYoutube = new XmlDocument();
        docYoutube.Load(readerYoutube);
        XmlNodeList nodesYoutube = docYoutube.SelectNodes("/feed/entry");

any ideas?


You're attempting to select the node 'entry' in an empty namespace, whereas you should be trying to select the node 'entry' in the namespace 'http://www.w3.org/2005/Atom'.

You can use XMLNamespaceManager to specify a default namespace:

XmlNamespaceManager nsmanager = new XmlNamespaceManager(docYoutube.NameTable);
nsmanager.AddNamespace(String.Empty, "http://www.w3.org/2005/Atom");

or you could use "/*[local-name()='feed']/*[local-name()='entry']"


Specify the namespace.


If you want to visualize the result of XPath queries, you can use the XpathVisualizer. It's a WinForms tool. Load the XML document you want to query, key in the query, view the results.

What's wrong with this XPath query?

Free. Open source.


If it does not generate an error, it must be because the xml-document doesn't contain a <feed>-element, or <entry> elements with a <feed>-parent.


Try getting at the base of the problem by using the // instead of /. So something like //entry my work better as it will plumb the depths looking for your request.

But my question is whether that XPath query is actually retrieving anything.


string youtube = "http://gdata.youtube.com/feeds/api/users/CTVOlympics/uploads";
string twitter = "http://twitter.com/statuses/user_timeline/ctvolympics.rss";

//this populates the XmlNodeList object
XmlDocument docTwitter;
using (var readerTwitter = XmlReader.Create(twitter))
{
    docTwitter = new XmlDocument();
    docTwitter.Load(readerTwitter);
}
XmlNodeList nodesTwitter = docTwitter.SelectNodes("/rss/channel/item");

//this doesn't populate the object
XmlDocument docYoutube;
using (var readerYoutube = XmlReader.Create(youtube))
{
    docYoutube = new XmlDocument();
    docYoutube.Load(readerYoutube);
}
XmlNamespaceManager ns = new XmlNamespaceManager(docYoutube.NameTable);
ns.AddNamespace("atom", "http://www.w3.org/2005/Atom");
XmlNodeList nodesYoutube = docYoutube.SelectNodes("/atom:feed/atom:entry", ns);


Give this a try: "/*[local-name()='feed']/*[local-name()='entry']"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜