How to convert XML to Dictionary
14,118
var xdoc = XDocument.Load(path_to_xml);
_dictionary = xdoc.Descendants("data")
.ToDictionary(d => (string)d.Attribute("name"),
d => (string)d);
Related videos on Youtube
Author by
Ramzy Abourafeh
Updated on September 16, 2022Comments
-
Ramzy Abourafeh over 1 year
I've xml as following:
<?xml version="1.0" encoding="UTF-8"?> <root> <data name="LogIn">Log In</data> <data name="Password">Password</data> </root>
I success to do that without Linq, any one can help me to convert the following code to Linq:
using (XmlReader reader = XmlReader.Create(_xml)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "data") { reader.MoveToAttribute("name"); string key = reader.Value; reader.MoveToContent(); string value = reader.ReadElementContentAsString(); _dictionary.Add(key, value); } } reader.Close(); }
-
Daniel Brückner over 11 yearsPlain text passwords in an XML file...
-
-
Ramzy Abourafeh over 11 yearsI got the following error: 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' does not contain a definition for 'ToDictionary' and no extension method 'ToDictionary' accepting a first argument of type 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' could be found (are you missing a using directive or an assembly reference?)
-
ken2k over 11 years@RamzyAbourafeh Add
using System.Linq;
so you can use LINQ extension methods. -
Habib over 11 years@lazyberezovsky, what does
Descendants("data")
do ? -
Sergey Berezovskiy over 11 years@Habib, it returns descendant elements for this document which have name
data
msdn - same as xpath//data
-
efkah over 11 yearsawesome! @Habib, maybe xdoc.Element("Root").Elements() is better suited for you? but does the same here.
-
Habib over 11 years@lazyberezovsky, +1 and thanks for the link, and thanks efkah