Get a specific number of results from an XmlDocument XPath query

狂风中的少年 提交于 2019-12-01 05:56:02

Try this XPath query instead:

(/rss/channel/item)[position() <= 5]

It returns only the first five matching items. The parentheses are important, as without them the [position() <= 5] part applies to the item element's position in its parent rather than its position in the result node set.

Martin Peck

If you want to continue using xpath then you should look at the position() method in xpath. Using a predicate something like this...

[position() < 6]

... should result limit the results to only the first 5 items. Welbog's answer is your best reference here (+1 to Welbog).

However, if you're able to use .NET 3.5 then I would recommend you look at my answer here...

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

... and take a look at the syndication APIs that make dealing with RSS feeds much easier. Then, if you only want 5 items, use the LINQ method Take on the collection to take a specific number of items.

This will allow you to express yourself better and not have to worry about the structure of the feed, namespaces etc.

I realise this isn't directly answering your question but as many people don't know about these new APIs in .NET I thought I'd mention them here.

So, your code to get just 5 items would be something like this...

var xmlr = XmlReader.Create("http://twitter.com/statuses/public_timeline.rss")
var first5Items = SyndicationFeed
                    .Load(xmlr)
                    .GetRss20Formatter()
                    .Feed
                    .Items
                    .Take(5);  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!