Get Started With XML Using C#

Introduction

This article is part of the XML Tutorial series. In my first tutorial I am creating a XML file using C#. It’s like we take some input from the user and generate a XML file according to that.

XML

Background

We all know that the EXtensible Markup Language (XML) is a standard method to encode structured information. It is a standardize so it can be used in other platforms.

In C#, we will use the XDocument and XElement classes to create it. So you must include the System.Xml.Linq namespace to your project.

Before Starting, get some basic terms:

  • Root Element
  • Child Element
  • Parent Element
  • Attribute (but, we will avoid it for now)

I will use the following listing in my reference:

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <Students>     
  3.   <Student>  
  4.       <Name>Abhishek</Name>  
  5.     <Location State=”Jharkhand”>>Dhanbad</Location>  
  6.     </Student>   
  7.   <Student>  
  8.     <Name>Aman</Name>  
  9.     <Location State=”Bihar”>samastipur</Location>  
  10.   </Student>  
  11.    <Student>  
  12.    <Name>Vicky</Name>  
  13.     <Location State=”Bihar”>>Munger</Location>  
  14.   </Student>   
  15.   <Student>  
  16.     <Name>Ravi</Name>  
  17.     <Location State=”Bihar”>>Rafiganj</Location>  
  18.   </Student>  
  19.   </Students>  
Root Element is the top most element or you can say is the grandparent of all elements. Every element resides inside its block. In my listing, <Students> is the root element.

Child Element is something that is inside some element. It’s a Relative term. Some element can be parent to some element, at the same time it can be a child for some element.

In the above listing, <Student> is a child element of a <Students> element. But, it is the parent element for <Name> and <Location>.

The same as for a child element, the parent element is also the relative term.

The <Student> element is the parent of the <Name> and <Location> elements.

Now, we come to the last term, Attribute.

It’s a special way to put extra data in a tag. Since, it doesn’t help much we have this feature to do it. Programmers usually avoid it to make their code simple.

As said in books, the use of attributes make your XML code accessibility faster and the CPU feels relaxed by doing this.

Like we put one State attribute in the Location element, <Location State=”Bihar”> … </Location>.

In another way we can put this as:

<Location>
<State>Bihar</State>
</Location>

Both does the same thing, but in a different way. I prefer the simplest one,  without any attributes.

The following is the C# Code to put your data in a XML file:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Xml.Linq;  
  6. namespace XMLdemo1  
  7. {  
  8.     class Program  
  9.     {  
  10.         //Model Class  
  11.         class Student  
  12.         {  
  13.             public Student(string name, string location)  
  14.             {  
  15.                 //With this, we are trying to target the class's field  
  16.                 this.Name = name;  
  17.                 this.Location = location;  
  18.             }  
  19.             public string Name { getset; }  
  20.             public string Location { getset; }  
  21.         }  
  22.         public static void Main(string[] args)  
  23.         {  
  24.             // Populate the List  
  25.             List<Student> student = CreateStudent();  
  26.             // creating the Document  
  27.             var studentXml = new XDocument();  
  28.             //Now, we are Adding the Root Element  
  29.             var rootElement = new XElement("Students");  
  30.             studentXml.Add(rootElement); //done with it  
  31.             // Now we will add the child Element  
  32.             foreach (Student temp in student)  
  33.             {  
  34.                 // Create Child Element  
  35.                 var studntElem = new XElement("Student");  
  36.                 //Now, add their child Element  
  37.                 var nameElement = new XElement("Name", temp.Name);  
  38.                 studntElem.Add(nameElement);  
  39.                 //Again, add Location in the same way  
  40.                 var locationElement = new XElement("Location", temp.Location);  
  41.                 studntElem.Add(locationElement);  
  42.                 // add the Main Child element to root  
  43.                 rootElement.Add(studntElem);  
  44.             }  
  45.             // Now, we will read the Created File  
  46.             Console.WriteLine(studentXml.ToString());  
  47.             studentXml.Save("myData.xml");  
  48.             Console.ReadKey();  
  49.         }  
  50.         private static List<Student> CreateStudent()  
  51.         {  
  52.             List<Student> stud = new List<Student>()  
  53.             {  
  54.                 new Student("Abhishek","Dhanbad"),  
  55.                 new Student("Aman","Samastipur"),  
  56.                 new Student("Vicky","Munger"),  
  57.                 new Student("Chandan","Bhagalpur"),  
  58.                 new Student("Ravi","Dhanbad")  
  59.             };  
  60.             //returning the Generic list  
  61.             return stud;  
  62.         }  
  63.     }  
  64. }  
Explanation

First we have a Model class named Student with some property. It actually holds that value which we want the child element field in our XML file.

For now, we consider Name and location.

Moving to the main() method, we first try to populate the List using a method which returns a List<Student>, CreateStudent().

In that method, we created a List of the same generic way named stud and added the value using the constructor of the Student class.

And last, we return that generic type.

Now, we come to the real XML thing.

So, the first step is to create an XDocument object. We had done it by studentXml.

Then, we created a root element object, rootElement (object of XElement) and ed an argument in the constructor as a Root Elements string.

After every creation we need to add a child element to its parent (or upper hierarchy). So, here we need to add a root element to studntXml, a XDocument’s object.

Next we had a foreach() loop to add all child elements in <Student>.

In every tag we used the same XElement with two arguments. The first is a "Name" of the tag and the next is its corresponding value.

After doing this, add the element to its upper hierarchy element (or parent element).

At last, we used the WriteLine() method to display the whole format of the XML file. Thereafter, saved it to a physical XML file using the Save() method.

Output of Console

Output

And, the physical XML file is:
 
Physical XML file

Conclusion

Next we will try to read from a XML file using XmlReader. And, try to use LINQ to XML.

For now, that is enough to start. For nay confusion try to check the enclosed solution file.


Similar Articles