我正在努力思考 Linq to XML。我有一个如下所示的 XML 文档:
<update>
<comments total="4">
<comment>
<person>
<id>SomeID1</id>
<name>SomeName1</name>
<picture>PictureURL1</picture>
</person>
<message>Comment number 1</message>
</comment>
<comment>
<person>
<id>SomeID2</id>
<name>SomeName2</name>
<picture>PictureURL2</picture>
</person>
<message>Comment number 2</message>
</comment>
<comment>
<person>
<id>SomeID3</id>
<name>SomeName3</name>
<picture>PictureURL3</picture>
</person>
<message>Comment number 3</message>
</comment>
<comment>
<person>
<id>SomeID4</id>
<name>SomeName4</name>
<picture>PictureUR4L</picture>
</person>
<message>Comment number 4</message>
</comment>
</comments>
</update>
我想做的是只接受前两条评论。这是我的代码:
var commentsList = (from comments in doc.Descendants("comments").Take(2)
select comments.Elements("comment"));
如果文档有两个或更少的评论,这工作正常,但当有两个以上的评论时,我得到以下异常:
Unable to cast object of type 'd__11' to type 'System.Xml.Linq.XElement
我错过了什么吗?
编辑:我忘了提到当我尝试使用 foreach 循环遍历 commentsList 时抛出异常。我也尝试使用 .ToList() 但仍然遇到相同的异常。
最佳答案
可以直接跳转到评论元素。
var commentsList = doc.Descendants("comment").Take(2);
关于c# - Linq to XML 使用 Take() 获取前两个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12207156/