views:

28

answers:

2

I need to load an XML document into my Dictionary<string,string> object.

XML looks like:

<nodes>
<node id="123">
   <text>text goes here</text>
</node>
</nodes>

How can I do this using XmlDocument?

I want readability over performance, and I find XmlReader to be hard to read b/c you have to keep checking the node type.

A: 

Assuming ID is the key and the value of the <text> node is the value, you can use LINQ:

XDocument xDoc;
using(StringReader sr = new StringReader("thexml"))
{
    xDoc = XDocument.Load(sr);
}
myDictionary = xDoc.Descendants("node").ToDictionary(x => x.Attribute("id").Value, x => x.Descendants("text").First().Value);
Rex M
Except, of course, for the part where that is the 3.5 framework and he wants 2.0...
GalacticCowboy
+1  A: 

Well, there is a reason why XML parsing has improved since 2.0, but if you just want a sample that parses that fragment without using XmlReader, this should work. I'm sure there are other ways of doing this:

XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<nodes><node id=""123""><text>text goes here</text></node><node id=""321""><text>more text goes here</text></node></nodes>");

foreach (XmlNode nodes in doc.GetElementsByTagName("nodes"))
{
    foreach (XmlNode node in nodes.ChildNodes)
    {
        XmlNodeList list = node.SelectNodes("text");
        if (list.Count > 0)
        {
            Console.Write("{0}='{1}'\n", node.Attributes["id"].Value, list[0].InnerText);
        }
    }
}
Console.WriteLine("Done.");
Console.ReadKey();
ongle