【问题标题】:Linq to XML using Take() to get first two elementsLinq to XML 使用 Take() 获取前两个元素
【发布时间】: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


    【解决方案1】:

    试试这个:

    var commentsList = from comments in doc.Descendants("comments")
                       select comments.Elements("comment").Take(2);
    

    【讨论】:

    • 我尝试了这个 Ian,但仍然遇到同样的异常。我忘了提到当我尝试使用 foreach 循环遍历 cmetsList 时会引发异常。我也尝试使用 .ToList() 但仍然遇到相同的异常。我会更新我的问题。
    【解决方案2】:

    你可以直接跳到评论元素。

    var commentsList = doc.Descendants("comment").Take(2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多