Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read XML file in .net Core MVC?

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?

like image 285
pollikop Avatar asked Mar 09 '23 20:03

pollikop


2 Answers

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);
like image 147
J. Doe Avatar answered Mar 31 '23 19:03

J. Doe


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);
like image 31
Ayoub Errazki Avatar answered Mar 31 '23 21:03

Ayoub Errazki