5

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?

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

A detailed example of how to use it here stackoverflow.com/questions/39552474/…
3

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);

2 Comments

Code-only answers are not particularly helpful. Please include a brief description of how this code solves the problem.
@Shree Does the answer above with "Try ... example" satisfy your requirement?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.