Convert XmlDocument to dictionary <string, string>
I am looking for a good way to convert XmlDocument
to Dictionary<string, string>
using Linq.
My xml is formatted as follows:
<config> <field>value</field> <field2>value2</field2> </config>
I would like to put this in a dictionary with key value pairs that look like this:
value
field2, value2
I think I should use Linq for this, but I'm not sure about the syntax.
I do not know if it is the best, but its clean and 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 XmlDocument
, according to your question, you can use this approach to get 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 XElement
, you can use the Parse
method to load XML from a string or use the Load
method to load it from a file. Then this approach should be enough:
var xml = XElement.Parse(input); var dict = xml.Elements() .ToDictionary(n => n.Name.LocalName, n => n.Value);
One way to do this with linq: Create an XML document using
XElement xDoc = XElement.Parse("<config><field>value</field><field2>value2</field2</config>");
For simplicity, I directly embedded the XML fragment in parsing.
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 this query to a dictionary using a simple one for each loop.
Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (var CurNode in query) { dictionary.Add(CurNode.tag, CurNode.value); }