tags:

views:

20

answers:

1

I'm attempting to read the content of a XML file, using XmlTextReader in C#, that has the following structure:

<root>
  <person id="0">
    <a1>val</a1>
    <a2>val</a2>
  </person>
  <person id="1">
    <a1>val</a1>
    <a2>val</a2>
  </person>
</root>

I'm looking to read the file into a nested dictionary:

Dictionary<string, Dictionary<string, string>> xmldata = new Dictionary<string, Dictionary<string, string>>();

Hoping to produce:

xmldata = {0 => {a1 => val, a2 => val}, 1 => {a1 => val, a2 => val}}

Issues:

1) Not sure this is the best method for storing the xml data read in, would I be better with

<a x="1"></a><a x="2"></a>

for example?
2) Having a few problems successfully populating the relavent dictionaries

+1  A: 

You want to use LINQ-to-XML for all things XML in .NET:

var doc = XDocument.Parse(@"<root>
  <person id=""0"">
    <a1>val</a1>
    <a2>val</a2>
  </person>
  <person id=""1"">
    <a1>val</a1>
    <a2>val</a2>
  </person>
</root>");

var result = doc.Root
                .Elements()
                .ToDictionary(
                    e => e.Attribute("id"),
                    e => e.Elements()
                          .ToDictionary(
                              f => f.Name.LocalName,
                              f => f.Value));

The constructs nested dictionaries like as if result was created like this:

var result = new Dictionary<string, Dictionary<string, string>>
{
    { "0", new Dictionary<string, string> { { "a1", "val" }, { "a2", "val" } } },
    { "1", new Dictionary<string, string> { { "a1", "val" }, { "a2", "val" } } },
};
dtb
Superb my good man! I wasn't aware there was a LINQ-to-XML library so thanks for introducing me to that. Plus thanks for the code example, had a play about and got it working just how I desire it.
Abs