将 XML 反序列化为字典

问题描述

我尝试将 XML 反序列化为字典。

这是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfTableRow1 xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TableRow1>
    <Code>A</Code>
    <Explanation>Spital</Explanation>
  </TableRow1>
  <TableRow1>
    <Code>B</Code>
    <Explanation>Heim</Explanation>
  </TableRow1>
  <TableRow1>
    <Code>C</Code>
    <Explanation>Spitex</Explanation>
  </TableRow1>
</ArrayOfTableRow1>

现在我将它加载到 XDocument 中。这工作正常。在我尝试反序列化为字典之后。这给了我一个ArgumentException: An item with the same key has already been added. Key: TableRow1

var xdc = XDocument.Load(...);
var dic = xdc.Descendants("ArrayOfTableRow1").Descendants()
              .ToDictionary(element => element.Name,element => element.Value);

有人可以帮助我,如何将我的 XML 序列化为 Dictionary

{{"A","Spital"},{"B","Heim"},...}

解决方法

试试这个:

var dic = xdc.Descendants("ArrayOfTableRow1")
             .Elements()
             .ToDictionary(x => x.Element("Code").Value,x => x.Element("Explanation").Value);

您不想要 DescendantsArrayOfTableRow1,您只想要直接的孩子,所以使用 Elements。然后,当您遍历每个 TableRow1 时,获取 CodeExplanation 值。

请注意,这不包括任何错误处理。

,

尝试以下操作:

            XDocument doc = XDocument.Load(FILENAME);
            Dictionary<string,string> dict = doc.Descendants("TableRow1")
                .GroupBy(x => (string)x.Element("Code"),y => (string)y.Element("Explanation"))
                .ToDictionary(x => x.Key,y => y.FirstOrDefault());