Cole W
Cole W

Reputation: 15303

Converting XmlDocument to Dictionary<string, string>

I'm looking for a good way to convert an XmlDocument to Dictionary<string, string> using Linq.

My xml is formatted like this:

<config>
    <field>value</field>
    <field2>value2</field2>
</config>

I'd like to put this into a Dictionary with key value pairs looking like this:

field, value
field2, value2

I'm thinking I should use Linq to do this but I'm not sure about the syntax.

Upvotes: 1

Views: 6987

Answers (3)

Ahmad Mageed
Ahmad Mageed

Reputation: 96487

Using an XmlDocument, per your question, you can use this approach to get a Dictionary<string, string>.

string input = @"<config>
    <field>value</field>
    <field2>value2</field2>
</config>";

var xml = new XmlDocument();
xml.LoadXml(input);

var dict = xml.SelectNodes("/config/*")
              .Cast<XmlNode>()
              .ToDictionary(n => n.Name, n => n.InnerText);

If you can use an XElement, you can use either the Parse method to load the XML from a string, or use the Load method to load it from a file. Then this approach should suffice:

var xml = XElement.Parse(input);
var dict = xml.Elements()
              .ToDictionary(n => n.Name.LocalName, n => n.Value);

Upvotes: 6

Guido Zanon
Guido Zanon

Reputation: 3059

I dont know if its the better way, but its clean & simple..

XElement xdoc = XElement.Load("yourFilePath");
Dictionary<string, string> result = (from element in xdoc.Elements() select new KeyValuePair<string, string>(element.Name.ToString(), element.Value)).ToDictionary(x => x.Key, x => x.Value);

Upvotes: 4

Mark Smith
Mark Smith

Reputation: 1115

One way of doing it with linq would be the following Create an XML document using

XElement xDoc = XElement.Parse("<config><field>value</field><field2>value2</field2</config>");

For simplicity, I inlined your XML snippet into the parse directly.

Then you can create a query with the following

var query = from xEle in xDoc.Descendants()
select new { tag = xEle.Name.LocalName, value = xEle.Value };

Then convert that query to a dictionary using a simple for each loop.

Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (var CurNode in query)
{
    dictionary.Add(CurNode.tag, CurNode.value);
}

Upvotes: 2

Related Questions