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();
}
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.
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().
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.
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.
var xdoc = XDocument.Load(path_to_xml);
_dictionary = xdoc.Descendants("data")
.ToDictionary(d => (string)d.Attribute("name"),
d => (string)d);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With