例如,我有这个 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/