Search code examples
c#dictionaryxmlserializer

Deserialize XML to Dictionary


I try to deserialize XML to dictionary.

Here is my 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>

Now I load it in a XDocument. This is working correct. After I try it to deserialize to Dictionary. This gives me an 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);

Can someone help me, how I can serialize my XML to a Dictionary<string, string> with

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

Solution

  • Try this:

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

    You don't want Descendants of ArrayOfTableRow1, you want only the immediate children, so use Elements. Then, as you loop over each TableRow1, grab the Code and Explanation values.

    Note that this doesn't include any error handling.