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.
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:
- <?xml version="1.0" encoding="utf-8" ?>
- <Students>
- <Student>
- <Name>Abhishek</Name>
- <Location State=”Jharkhand”>>Dhanbad</Location>
- </Student>
- <Student>
- <Name>Aman</Name>
- <Location State=”Bihar”>samastipur</Location>
- </Student>
- <Student>
- <Name>Vicky</Name>
- <Location State=”Bihar”>>Munger</Location>
- </Student>
- <Student>
- <Name>Ravi</Name>
- <Location State=”Bihar”>>Rafiganj</Location>
- </Student>
- </Students>
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:



Comments
Join the conversation! Your thoughts help the community grow.