Monday, June 28, 2021

Create XML file and save into special folder



using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;

namespace XMLDocumentCreation
{
    class Program
    {
        //Model Class  
        class Student
        {
            public Student(string name, string location)
            {
                //With this, we are trying to target the class's field  
                this.Name = name;
                this.Location = location;
            }
            public string Name { get; set; }
            public string Location { get; set; }
        }

        public static void Main(string[] args)
        {
            List students = CreateStudent();
            var studentXml = new XDocument();
            var rootElement = new XElement("Students");
            studentXml.Add(rootElement); 
            foreach (Student std in students)
            {
                var studntElem = new XElement("Student");
                var nameElement = new XElement("Name", std.Name);
                studntElem.Add(nameElement);
                var locationElement = new XElement("Location", std.Location);
                studntElem.Add(locationElement);
                rootElement.Add(studntElem);
            }
            // Now, save the created XML File in XMLFiles folder
            string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string folder = "XMLFiles";
            string fullpath = Path.Combine(path, folder);
            DirectoryInfo di =  Directory.CreateDirectory(fullpath);
            studentXml.Save(fullpath + "/students.xml");
            Console.WriteLine(studentXml.ToString());
            Console.ReadKey();
        }
        private static List CreateStudent()
        {
            List stud = new List()
            {
                new Student("Ajay","Patna"),
                new Student("Rakesh","Patna"),
                new Student("Rajeev","Delhi"),
                new Student("Mahesh","Mumbai"),
                new Student("Tara","Patna")
            };
            return stud;
        }
    }
       
}
OUTPUT

<Students>
  <Student>
    <Name>Ajay</Name>
    <Location>Patna</Location>
  </Student>
  <Student>
    <Name>Rakesh</Name>
    <Location>Patna</Location>
  </Student>
  <Student>
    <Name>Rajeev</Name>
    <Location>Delhi</Location>
  </Student>
  <Student>
    <Name>Mahesh</Name>
    <Location>Mumbai</Location>
  </Student>
  <Student>
    <Name>Tara</Name>
    <Location>Patna</Location>
  </Student>
</Students>






No comments:

Post a Comment

Hot Topics