CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Reading and Writing XML files in C# and ASP.Net

By Satheesh Babu
Posted On Dec 30,2010
Article Rating:
Average Rating: 2
No of Ratings: 1
No of Comments: 3
Category: ASP.Net
Print this article.

Reading and Writing XML files in C# and ASP.Net

 

XML is very versatile and most commonly used data format in any applications we develop. Hence, there will be always a need to read and write xml files in our day today development tasks. Moving forward, this little article will help us understand how to read and write xml files using C# in ASP.Net.

.Netframework has packed with a class called XmlTextWriter in System.XML namespace to create xml files dynamically. Next section will help us to understand the same.

Writing XML files in C#

The XmlTextWriter class includes number of methods to create xml document content very easily. Consider we need to create a xml file called Employee.xml with the below data,

<?xml version="1.0" encoding="utf-8"?>

<Employees>

  <Employee type="Permanent">

    <ID>100</ID>

    <FirstName>Satheesh</FirstName>

    <LastName>Babu</LastName>

    <Dept>IT</Dept>

  </Employee>

</Employees>

 

If you see the above xml content, you can visualize it as an xml document having xml elements (Employees, Employee) or nodes with attributes (Type) and values (Satheesh). Keeping this in mind, to create the above XML document programmatically using XmlTextWriter class we need to first call WriteStartDocument() to start the document creation which emits the xml declaration. Next, you can subsequently use WriteStartElement(), WriteAttributeString() method to construct the whole document. Remember, any xml nodes created should have the matching closing nodes. This is done by calling WriteEndElement() and WriteEndDocument() methods.

Refer the below code.

protected void Page_Load(object sender, EventArgs e)

    {

        XmlTextWriter xmlwriter = new XmlTextWriter(Server.MapPath("App_Data/Employee.xml"), Encoding.UTF8);

        xmlwriter.Formatting = Formatting.Indented;

        xmlwriter.WriteStartDocument();       

        xmlwriter.WriteStartElement("Employees");

 

        xmlwriter.WriteStartElement("Employee");

        xmlwriter.WriteAttributeString("type", "Permanent");

        xmlwriter.WriteElementString("ID", "100");

        xmlwriter.WriteElementString("FirstName", "Satheesh");

        xmlwriter.WriteElementString("LastName", "Babu");

        xmlwriter.WriteElementString("Dept", "IT");

        xmlwriter.WriteEndElement();

 

        xmlwriter.WriteEndElement();

        xmlwriter.WriteEndDocument();

        xmlwriter.Flush();

        xmlwriter.Close();

   }

 

Once executed, it will create an xml document called Employee.xml in your project App_Data folder. You need to include the System.Xml and System.Text namespace for the above code to work.

In the above example, we have created a very basic xml document using XmlTextWriter class. This class has many more useful methods which can be used. The below code creates an xml document from a DataTable manually including XML comments.

protected void Page_Load(object sender, EventArgs e)

    {

       XmlTextWriter xmlwriter = new XmlTextWriter(Server.MapPath("App_Data/Employee.xml"), Encoding.UTF8);

        xmlwriter.Formatting = Formatting.Indented;

        xmlwriter.WriteStartDocument();

        xmlwriter.WriteComment("Programmatically writing XML");

        xmlwriter.WriteStartElement("Employees");

//GetEmployees() method returns DataTable with data. Download the code attached to see it in action

        DataTable dt = GetEmployees();

        for (int i = 0; i < dt.Rows.Count; i++)

        {

            xmlwriter.WriteStartElement("Employee");

            xmlwriter.WriteAttributeString("type", dt.Rows[i]["Type"].ToString());

            xmlwriter.WriteElementString("ID", dt.Rows[i]["ID"].ToString());

            xmlwriter.WriteElementString("FirstName", dt.Rows[i]["FirstName"].ToString());

            xmlwriter.WriteElementString("LastName", dt.Rows[i]["LastName"].ToString());

            xmlwriter.WriteElementString("Dept", dt.Rows[i]["Dept"].ToString());

            xmlwriter.WriteEndElement();

        }

        xmlwriter.WriteEndElement();

        xmlwriter.WriteEndDocument();

        xmlwriter.Flush();

        xmlwriter.Close();

    }

 




OUTPUT

<?xml version="1.0" encoding="utf-8"?>

<!--Programmatically writing XML-->

<Employees>

  <Employee type="Permanent">

    <ID>100</ID>

    <FirstName>Satheesh</FirstName>

    <LastName>&lt;b&gt;Babu</LastName>

    <Dept>IT</Dept>

  </Employee>

  <Employee type="Temporary">

    <ID>101</ID>

    <FirstName>Peters</FirstName>

    <LastName>Laurence</LastName>

    <Dept>Development</Dept>

  </Employee>

  <Employee type="Permamnet">

    <ID>102</ID>

    <FirstName>Rick</FirstName>

    <LastName>Anderson</LastName>

    <Dept>Sales</Dept>

  </Employee>

  <Employee type="Temporary">

    <ID>103</ID>

    <FirstName>Ramesh</FirstName>

    <LastName>Kumar</LastName>

    <Dept>HR</Dept>

  </Employee>

</Employees>

 

You can see the comments added in the above xml document.

 

Reading XML files in C#

Like XmlTextWriter class, the System.Xml namespace includes XmlTextReader class which can be used to read xml document. The below code reads all the text nodes from the Employee.xml file.

protected void Page_Load(object sender, EventArgs e)

    {

        using (XmlTextReader reader = new XmlTextReader(Server.MapPath("App_Data/Employee.xml")))

        {

            while (reader.Read())

            {

                if (reader.NodeType == XmlNodeType.Text)

                {

                    Response.Write(reader.Value);

                    Response.Write("<br>");

                }

            }

        }

    }

 

You can also read xml using xpath expressions. Refer the below article on codedigest.com which talks about reading xml document using xpath expressions.

Reading XML files in ASP.Net Using XPath

 

Downloads

Download Source

 

Conclusion

Since xml is widely used data format in any application we develop it is obvious that reading and writing to xml files will be most repetitive tasks. Thus, with this article we have understood how to read and write xml files dynamically using XmlTextReader and XmlTextWriter class.

Download the source attached with this article and see it in action.

Happy Coding!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Article Feedback
Article Feedback
How to read data from XML file using C# code
Informative post. You made it very simple and understandable. Check out this link too it also having good post on reading data form xml file using c# code.
http://mindstick.com/Articles/851bfc02-9c84-41c4-a3ca-d83b5fd0adf2/?How%20to%20read%20data%20from%20XML%20file%20in%20C%20Sharp

Thanks Everyone for your good post!
ghgh
ghghgh