Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert XML to Dictionary

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();
}
like image 909
Ramzy Abourafeh Avatar asked Dec 19 '12 12:12

Ramzy Abourafeh


People also ask

What is XML to dict?

The xmltodict. parse() is a built-in function that convert the XML to Python dictionary. In the output, it can be seen that the XML is successfully converted into a dictionary.

How do I open a XML file in Python?

To read an XML file using ElementTree, firstly, we import the ElementTree class found inside xml library, under the name ET (common convension). Then passed the filename of the xml file to the ElementTree. parse() method, to enable parsing of our xml file. Then got the root (parent tag) of our xml file using getroot().

How do I parse XML to JSON in Python?

Method 1: Using xmltodict and json module To handle the JSON file format, Python provides a module named json. STEP 3: Read the xml file here, “data_dict” is the variable in which we have loaded our XML data after converting it to dictionary datatype.

How do you parse an XML string in Python?

There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.


1 Answers

var xdoc = XDocument.Load(path_to_xml);
_dictionary = xdoc.Descendants("data")
                  .ToDictionary(d => (string)d.Attribute("name"),
                                d => (string)d);
like image 96
Sergey Berezovskiy Avatar answered Oct 10 '22 07:10

Sergey Berezovskiy