【问题标题】:Can't get all tags from XML file无法从 XML 文件中获取所有标签
【发布时间】:2014-05-25 11:01:19
【问题描述】:

我在从我的 XML 文件中获取所有标签时遇到问题。在我的 XML 文件中,我有一个选项标签,其中包含描述。

<selection id="1">
    <desc>You see a cat stuck up in a tree, do you</desc>
    <option>
        <desc goto_id="2">Help the cat</desc>
        <desc goto_id="3">Leave the cat stuck in the tree</desc>
    </option>
</selection>

我已经设法从选择中获取描述和 ID,但是当我尝试在对象上创建一个数组时,它只会在循环遍历它时获得第一个。

var selectionQueryNew = from selection in xml.Root.Descendants("selection")
                        select new {
                            Desc = selection.Element("desc").Value,
                            Id = selection.Attribute("id").Value,
                            Options = selection.Elements("option")
                                .Select(option => new {
                                    Desc = option.Element("desc").Value
                                }).ToArray()
                        };

我认为 .Select 区域有问题,知道为什么它只会从 XML 文件中选择第一个描述吗?

【问题讨论】:

    标签: xml linq


    【解决方案1】:

    您只看到第一个描述的原因是因为您的 LINQ 查询的这一部分:

    Options = selection.Elements("option")
                       .Select(option => new {
                           Desc = option.Element("desc").Value
                        }).ToArray()
    

    代码是说从selection 的集合中获取所有名为“option”的元素,然后从名为“option”的元素集合中选择一个元素。您要做的是在“选项”下获取“desc”元素的集合:

    var selectionQueryNew = from selection in xml.Root.Descendants("selection")
                            select new
                            {
                                Desc = selection.Element("desc").Value,
                                Id = selection.Attribute("id").Value,
                                Options = selection.Element("option").Elements("desc")
                                          .Select(option => new
                                          {
                                              Desc = option.Value
                                          }).ToArray()
                             };
    

    在上面的代码中,对从`selection.Element("option").Elements("desc")返回的元素集合进行了选择,它捕获了数组中的所有描述。

    【讨论】:

    • 谢谢!这解决了问题:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    相关资源
    最近更新 更多