I\'m looking for a good way to convert an XmlDocument
to Dictionary
using Linq.
My xml is formatted like this:
<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);
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);
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);
}