I got an xml file in path Project/MyProjectName/Location_Data.xml . Inside xml look like this:
<?xml version="1.0" encoding="UTF-8"?>
<Root>
<Item id="1" type="province" value="Province A">
<Item id="101" type="district" value="District A">
<Item id="10101" type="precinct" value="Precinct A" />
<Item id="10102" type="precinct" value="Precinct B" />
<Item id="10103" type="precinct" value="Precinct C" />
</Item>
<Item id="102" type="district" value="District B">
<Item id="10201" type="precinct" value="Precinct D" />
<Item id="10202" type="precinct" value="Precinct E" />
<Item id="10203" type="precinct" value="Precinct F" />
</Item>
</Item>
<Item id="2" type="province" value="Province B">
<Item id="201" type="district" value="District C">
<Item id="20101" type="precinct" value="Precinct A1" />
<Item id="20103" type="precinct" value="Precinct C1" />
</Item>
<Item id="202" type="district" value="District D">
<Item id="20201" type="precinct" value="Precinct D1" />
<Item id="20202" type="precinct" value="Precinct E1" />
<Item id="20203" type="precinct" value="Precinct F1" />
</Item>
</Item>
</Root>
I want to read this file. I tried to use the XmlTextReader
, but Net Core does not support it yet. I also tried to use XDocument.Load(Server.MapPath())
, but it does not work too. Any advice?
Try to use XmlSerializer
Simple example:
XmlSerializer xml = new XmlSerializer();
FileStream xmlStream = new FileStream("Patch/To/File.xml", FileMode.Open);
var result = xml.Deserialize(xmlStream);
Include the xml library : using System.Xml you can try 2 versions , either load the xml string as a whole "content" as parameter i mean, or read xml from a file path.
This version reads from xml string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
This one reads from a file
doc.Load(xml);
and to verify if it works
//get the first node
XmlNode root = doc.FirstChild;
//then output it
Console.WriteLine(root.OuterXml);
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