【发布时间】:2012-08-25 18:55:03
【问题描述】:
我正试图围绕 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>
我想要做的是只取前两个 cmets。这是我的代码:
var commentsList = (from comments in doc.Descendants("comments").Take(2)
select comments.Elements("comment"));
如果文档有两个或更少的 cmets,这可以正常工作,但是当有两个以上的 cmets 时,我会收到以下异常:
无法将“d__11”类型的对象转换为“System.Xml.Linq.XElement”类型
我错过了什么吗?
编辑:我忘了提到当我尝试使用 foreach 循环遍历 cmetsList 时会引发异常。我也尝试过使用 .ToList() 但仍然遇到相同的异常。
【问题讨论】:
标签: c# linq-to-xml