从 XmlDocument XPath 查询获取特定数量的结果
我正在查询 Twitter RSS 源并将结果提供到转发器中进行显示。我只想获取 XPath 查询的前 5 个结果。有没有办法在 XPath 语法中做到这一点,或者我是否必须循环生成的 XmlNodeList
才能提取前 5 个?
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(rssPath);
doc.Load(reader);
XmlNodeList items = doc.SelectNodes("/rss/channel/item");
rptTwitter.ItemDataBound += new RepeaterItemEventHandler(rptTwitter_ItemDataBound);
rptTwitter.DataSource = items;
rptTwitter.DataBind();
I'm querying a Twitter RSS feed and supplying the results into a Repeater for display. I'd like to only get the first 5 results of the XPath query. Is there a way to do that in the XPath syntax or do I have to loop over the resulting XmlNodeList
to pull out the first 5?
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(rssPath);
doc.Load(reader);
XmlNodeList items = doc.SelectNodes("/rss/channel/item");
rptTwitter.ItemDataBound += new RepeaterItemEventHandler(rptTwitter_ItemDataBound);
rptTwitter.DataSource = items;
rptTwitter.DataBind();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请尝试使用此 XPath 查询:
它仅返回前五个匹配项。括号很重要,因为如果没有它们,
[position() <= 5]
部分将应用于item
元素在其父级中的位置,而不是其在结果节点中的位置放。Try this XPath query instead:
It returns only the first five matching items. The parentheses are important, as without them the
[position() <= 5]
part applies to theitem
element's position in its parent rather than its position in the result node set.如果你想继续使用xpath,那么你应该看看xpath中的position()方法。使用类似这样的谓词...
...应该将结果限制为仅前 5 项。韦尔博格的答案是您最好的参考(对韦尔博格+1)。
但是,如果您能够使用.NET 3.5,那么我建议您在此处查看我的答案...
在 <10 行内你能做的最酷的事情是什么几行简单的代码?帮助我激励初学者!
...并查看联合 API,它们使处理 RSS 提要变得更加容易。然后,如果您只需要 5 个项目,请使用 LINQ 方法 Take 处理集合以获取特定数量的项目。
这将使您能够更好地表达自己,而不必担心提要的结构、命名空间等。
我意识到这并不能直接回答您的问题,但由于很多人不了解 .NET 中的这些新 API,我认为我想在这里提到他们。
所以,你只获取 5 个项目的代码将是这样的......
If you want to continue using xpath then you should look at the position() method in xpath. Using a predicate something like this...
... 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...