Create or Write xml file in C-Sharp

XML is a platform independent language, Which means we can use xml file among different platforms like Windows, Linux, Mac and android. Once we create an XML file in one platform it can be access in other platforms also.

Here we will use XmlDocument to create an xml file from scratch. Using XmlDocument class we can load, validate, edit, add, and position XML in a document.

Moreover it  is an in-memory representation of an XML document. We can load XML into the DOM (document object model) by using the XmlDocument class, and then programmatically read, modify, and remove XML in the document.

Step 1:  We will first create Create a new Console application.

Step 2:  Add new class naming DTOStudent, DTO stands for Data Transfer object. with three properties Studentid, StudentName and StudentClass as follows.

public class DTOStudent {     public int Studentid { get; set; }     public string StudentName { get; set; }     public string StudentClass { get; set; } }

Step 3:  Now we will add another  Business Access Logic (BAL) class BALStudent and populate it with some data by creating a method GetStudents() as follows.

using System.Collections.Generic; public class BALStudent {     public static List<DTOStudent> GetStudents()     {         List<DTOStudent> s = new List<DTOStudent>();         s.Add(new DTOStudent() { Studentid = 1, StudentName = "Amit", StudentClass = "2nd" });         s.Add(new DTOStudent() { Studentid = 2, StudentName = "Anil", StudentClass = "2nd" });         s.Add(new DTOStudent() { Studentid = 3, StudentName = "Rohit", StudentClass = "2nd" });         s.Add(new DTOStudent() { Studentid = 4, StudentName = "Ashu", StudentClass = "2nd" });         return s;     } }

Step 1:  Add new class UIXmlWritter. Create properties XmlFilePath and its constructor to initialize its properties. Which is used to get physical location path, where xml file will be created.

public string XmlFilePath { get; set; } public UIXmlWritter(string XmlFilePath) {     this.XmlFilePath = XmlFilePath; }

Step 1:  Create Write method which will responsible for creating xml file. it will fetch data from BALStudent class method GetStudents. and write entire data into xml file.

public void Write() {     try     {         List<DTOStudent> students = new List<DTOStudent>();         students = BALStudent.GetStudents();         XmlDocument xmlDoc = new XmlDocument();         XmlNode rootNode = xmlDoc.CreateElement("Students");         xmlDoc.AppendChild(rootNode);         XmlNode userNode;         XmlAttribute attribute;         foreach (DTOStudent student in students)         {             userNode = xmlDoc.CreateElement("Student");             attribute = xmlDoc.CreateAttribute("StudentId");             attribute.Value = Convert.ToString(student.Studentid);             userNode.Attributes.Append(attribute);             attribute = xmlDoc.CreateAttribute("Class");             attribute.Value = student.StudentClass;             userNode.Attributes.Append(attribute);             userNode.InnerText = student.StudentName;             rootNode.AppendChild(userNode);         }         xmlDoc.Save(this.XmlFilePath);         Console.WriteLine("Student XML Created Successfully.");         Console.ReadKey();     }     catch (Exception ex)     {         Console.Write(ex.Message);     } }

Step 1:  Finally we will create an object of UIXmlWritter and pass location for file as an constructor argument.

static void Main(string[] args) {     UIXmlWritter x = new UIXmlWritter(@"D:\\StudentXml.xml");     Console.WriteLine("Start writing in xml file.");     x.Write();     Console.WriteLine("writing in xml file finished.");     Console.ReadKey(); }

By invoke Write() method of UIXmlWritter class. it will create a xml file in Drive D: With StudentXml.xml with following contents.

<Students>   <Student StudentId="1" Class="2nd">Amit</Student>   <Student StudentId="2" Class="2nd">Anil</Student>   <Student StudentId="3" Class="2nd">Rohit</Student>   <Student StudentId="4" Class="2nd">Ashu</Student> </Students>

You can copy entire code as follows.

//DTOStudent.cs public class DTOStudent {     public int Studentid { get; set; }     public string StudentName { get; set; }     public string StudentClass { get; set; } } //BALStudent.cs using System.Collections.Generic; public class BALStudent {     public static List<DTOStudent> GetStudents()     {         List<DTOStudent> s = new List<DTOStudent>();         s.Add(new DTOStudent() { Studentid = 1, StudentName = "Amit", StudentClass = "2nd" });         s.Add(new DTOStudent() { Studentid = 2, StudentName = "Anil", StudentClass = "2nd" });         s.Add(new DTOStudent() { Studentid = 3, StudentName = "Rohit", StudentClass = "2nd" });         s.Add(new DTOStudent() { Studentid = 4, StudentName = "Ashu", StudentClass = "2nd" });         return s;     } } //Program.cs using System; using System.Collections.Generic; using System.Xml; namespace Program {     class UIXmlWritter     {         public string XmlFilePath { get; set; }         public UIXmlWritter(string XmlFilePath)         {             this.XmlFilePath = XmlFilePath;         }         public void Write()         {             try             {                 List<DTOStudent> students = new List<DTOStudent>();                 students = BALStudent.GetStudents();                 XmlDocument xmlDoc = new XmlDocument();                 XmlNode rootNode = xmlDoc.CreateElement("Students");                 xmlDoc.AppendChild(rootNode);                 XmlNode userNode;                 XmlAttribute attribute;                 foreach (DTOStudent student in students)                 {                     userNode = xmlDoc.CreateElement("Student");                     attribute = xmlDoc.CreateAttribute("StudentId");                     attribute.Value = Convert.ToString(student.Studentid);                     userNode.Attributes.Append(attribute);                     attribute = xmlDoc.CreateAttribute("Class");                     attribute.Value = student.StudentClass;                     userNode.Attributes.Append(attribute);                     userNode.InnerText = student.StudentName;                     rootNode.AppendChild(userNode);                 }                 xmlDoc.Save(this.XmlFilePath);                 Console.WriteLine("Student XML Created Successfully.");                 Console.ReadKey();             }             catch (Exception ex)             {                 Console.Write(ex.Message);             }         }         static void Main(string[] args)         {             UIXmlWritter x = new UIXmlWritter(@"D:\\StudentXml.xml");             Console.WriteLine("Start writing in xml file.");             x.Write();             Console.WriteLine("writing in xml file finished.");             Console.ReadKey();         }     } }

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories