c# - 如何查询这个 XML 文件?

标签 c# xml linq linq-to-xml

我很难尝试创建查询。这是文件:

<Root>
<Summary>
    <Objective ID="1">
        <Exam Result="70" />
        <Exam Result="90" />
    </Objective>
    <Objective ID="2">
        <Exam Result="100" />
        <Exam Result="90" />
    </Objective>
</Summary>
</Root>

我需要获取 List> 中的值。第一个列表如果用于目标,最后一个列表用于存储每个结果。

有任何疑问,请告诉我

最佳答案

我怀疑你想要:

var results = doc.Descendants("Objective")
                 .Select(x => x.Elements("Exam")
                               .Select(exam => (double) exam.Attribute("Result"))
                               .ToList())
                 .ToList();

或者如果目标 ID 很重要,您可能需要考虑 Dictionary<int, List<double>> :

var results = doc.Descendants("Objective")
                 .ToDictionary(x => (int) x.Attribute("ID"),
                               x => x.Elements("Exam")
                                     .Select(y => (double) y.Attribute("Result"))
                                     .ToList());

或者一个Lookup<int, double> :

var results = doc.Descendants("Exam")
                 .ToLookup(x => (int) x.Parent.Attribute("ID"),
                           x => x.Select(y => (double) y.Attribute("Result"));

关于c# - 如何查询这个 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7800099/

相关文章:

c# - C#.Net Web服务错误处理

c# - 来自 WCF 请求的 IPrincipal

c# - WPF Canvas Children Bind ObservableCollection 可以包含不同形状和 TextBlocks 的 ViewModel 吗?

c# - 创建新的 XML 元素

c# - 将匿名类型设置为 null

c# - 使用 LINQ 提取特定类型的列表元素

iphone - 得到响应后如何使用json解析器解析数据?

javascript - 使用 Expo 的 FileSystem readasStringAsync 读取本地 .txt 文件

c# - 为什么 C# convertall 需要 2 个参数

Linq表达式多重左外连接错误