How to create XML document using C#.?

Sourav.Kayal
Posted by in C# category on for Beginner level | Points: 250 | Views : 9382 red flag

This article is to show how to create XML Document using C#

In my last XML article I was discussing the fundamental concept of XML and we discuss that all programming languages can parse and generate XML. Here we will look how to generate and extract data from XML using C# programming language. If c# is not your favorite language then please find proper syntax for your favorite language to do same.

Getting started to generate XML using C#

There are two class provided by .NET framework to work with XML. Those are XmlDocument and XmlTextWriter and to use those classes in our application we have to include System.xml namespace in current c# code file. If you are thinking why we need to include namespace then the answer is “When we will give reference of some namespace then we can able to access the classes belongs to same namespace”. To generate XML document we want to use XmlDocument and XmlTextWriter class so that proper namespace inclusion is must.

using System.Xml;


Generate XML document using XMLDocument class.

Demystify XmlDocument Class

It’s very important to know XmlDocument class structure to generate XML and play with it. Let’s have a glance on XmlDocument class. According to msdn below is the class hierarchy of XMLDocument class.

 System.Object

   System.Xml.XmlNode
      System.Xml.XmlDocument
         System.Xml.XmlDataDocument

And the class visibility scope is public.

public class XmlDocument : XmlNode

There are three constructor of this class those are

XmlDocument() 

XmlDocument(XmlImplementation)

XmlDocument(XmlNameTable)


Few properties of XmlDocument class are

Attributes

ChildNodes

DocumentElement

DocumentType

FirstChild

And many more

Few methods contain by XmlDocument are

AppendChild()

Clone()

CloneNode()

CreateComment()

Remove()

And many more

Now let’s learn how to use XmlDocument class to generate XML message of our own. See below example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Xml;
using namespace BlogProject
{
   class Program
    {
       static void Main(string[] args)
         {
 
             XmlDocument XD = new XmlDocument();
             XmlNode Root = XD.AppendChild(XD.CreateElement("Persons"));
             XmlNode Child = Root.AppendChild(XD.CreateElement("Person"));
             XmlNode name = Child.AppendChild(XD.CreateElement("Name"));
             name.InnerText = "Sourav Kayal";
             XD.Save(@"D:\Add.xml");
             Console.ReadLine();
         }
    }

And

the output is :

<Persons>

  <Person>

    <Name>Sourav Kayal</Name>

  </Person>

</Persons>





Generate XML document using XmlTextWriter class

Demystify XmlDocument Class

According to msdn documentation below is the class hierarchy of XmlTextWriter class.


System.Object
  System.Xml.XmlWriter
    System.Xml.XmlTextWriter

Class visibility scope is public

public class XmlTextWriter : XmlWriter

And from class definition it is clear that the class is derive from XmlWriter class.  Like XMLdocument class it also contain three constructor and those are

XmlTextWriter(TextWriter)

XmlTextWriter(Stream, Encoding)

XmlTextWriter(String, Encoding)

Few property of XmlTextWriter are

BaseStream

Formatting

IndentChar

Setting

And many more

Few Methods are

WriteDocType

WriteComment

WriteEndElement

And many more

Let’s see one example to create XML document using XmlTextWriter Class. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Xml;
using System.IO;
namespace BlogProject
{
   class Program
    {
       static void Main(string[] args)
         {
             StringWriter stringwriter = new StringWriter();
             XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter);
             xmlTextWriter.Formatting = Formatting.Indented;
             xmlTextWriter.WriteStartDocument();
             xmlTextWriter.WriteStartElement("Persons");
             xmlTextWriter.WriteStartElement("Person");
             xmlTextWriter.WriteElementString("Name", "Sourav");
             xmlTextWriter.WriteEndElement();
             xmlTextWriter.WriteEndDocument();
             XmlDocument docSave = new XmlDocument();
             docSave.LoadXml(stringwriter.ToString());
             docSave.Save(@"D:\Info.xml");
             Console.ReadLine();
         }
    }
}
<?xml version="1.0" encoding="utf-16"?>
<Persons>
  <Person>
    <Name>Sourav</Name>
  </Person>
</Persons>

First of all we have to include one namespace called System.IO in our c# file because in this example we are using StringWriter class and this class belongs to System.IO namespace. Let’s discuss code snippet line by line.

 StringWriter stringwriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter);

 In first line we are creating object of StringWriter class and in second line object of XmlTextWriter class.  And during object creation of XmlTextWriter class we are sending object of StringWriter class a argument of XmlTextWriter class constructor.

xmlTextWriter.Formatting = Formatting.Indented;

In this line we are setting Formatting property of xmlTextWriter object using the enumerator of Formatting class.If the Indented option is set, child elements are indented using the Indentation and IndentChar properties.

             xmlTextWriter.WriteStartDocument();
             xmlTextWriter.WriteStartElement("Persons");
             xmlTextWriter.WriteStartElement("Person");
             xmlTextWriter.WriteElementString("Name", "Sourav");

The first line of this code snippet is for starting of XML Document. The next two line will create two element followed by Persons element which is again root element like previous example.

Then the line  xmlTextWriter.WriteElementString("Name", "Sourav"); will add one element as a child element of Person element with value Sourav. And the newly added element name is “Name” as the first argument of WriterElementString() function.

 Below two lines of code is for closing the document.

   xmlTextWriter.WriteEndElement();
             xmlTextWriter.WriteEndDocument();

 Now we have to create object of XmlDocument class to load our formatted XML String and to save in persistent storage location using below code.

XmlDocument docSave = new
XmlDocument();
             docSave.LoadXml(stringwriter.ToString());

docSave.Save(@"D:\Info.xml");



Conclution:

Those examples are very simple and only for demonstration purpose. In real scenario may experience big XML document with hundreds of element and attributes.

Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)