C# 将 XML 值加载到字典中,名称作为索引

标签 c# xml linq dictionary

例如,我有这个 XML

<DEV>
   <families>
       <Family Name = "King">
         <Child Num = "1">
            <ChildName> John </ChildName>
            <Details>
                <Height> 1.80 </Height>
                <Weight> 78 </Weight>
                <Age> 16 </Age>
            </Details>
         </Child>
         <Child Num = "2">
            <ChildName> Jim </ChildName>
            <Details>
                <Height> 1.90 </Height>
                <Weight> 88</Weight>
                <Age> 18</Age>
            </Details>
         </Child>
       </Family>
       <Family Name = "Trud">
         <Child Num = "1">
            <ChildName> Bill </ChildName>
            <Details>
                <Height> 1.50 </Height>
                <Weight> 78 </Weight>
                <Age> 27 </Age>
            </Details>
         </Child>
         <Child Num = "2">
            <ChildName> Alise </ChildName>
            <Details>
                <Height> 1.40 </Height>
                <Weight> 56</Weight>
                <Age> 12</Age>
            </Details>
         </Child>
       </Family>
    </Families>
</DEV>

有没有办法拥有一个包含所有高度值的字典,以便我可以按 child 的名字进行搜索?例如 Weight_arr["Bill"] 会给我 78。

所有名字都是唯一的...意味着不可能有 2 个 Bill...

现在我知道我可以得到这样的权重数组...但我不能按名称搜索,只能按索引搜索。

    string[] arr = XDocument.Load(path + @"\Pages\Fams.xml").Descendants("Weight")
                .Select(element => element.Value).ToArray();

最佳答案

Dictionary<string, double> weigths = document
   .Descendants("Child")
   .ToDictionary(
       e => e.Element("ChildName").Value,
       e => (double) e.Element("Details").Element("Weight")  );

关于C# 将 XML 值加载到字典中,名称作为索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50510039/

相关文章:

c# - 在 xdocument 中移动节点

c# - 检查内部异常的最佳方法?

android - 如何在 kotlin 的 xml 标签中自动添加相同的 xml 代码?

c# - 复杂的 LINQ 查询与复杂的 for 循环

c# - 对象在转换为接口(interface)时必须实现 IConvertible (InvalidCastException)

sql-server - 从 XML FLWOR 查询返回计算的元素名称

javascript - C# - MVC - JSON - 使用 ViewBag 将列表从服务器端返回到客户端

c# - 无法手动或自动将 ILNumerics 控件添加到 VS2012 工具箱

c# - 如何在 RSA 实例的实例化中使用 Json Web key

c# - 为什么在我实现抽象方法时 Visual Studio 不将其标记为错误?