Click here to Skip to main content
Click here to Skip to main content

XML and .NET

, 6 Oct 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
XMl read, write, edit, search in .NET using C#

Introduction

In this post I will discuss about the term XML - Extensible Markup Language is a markup language like HTML designed for describing data as a database.

Topics to discuss :

  • Definition
  • How to write XML tags
  • Create a XML file in .NET
  • Data read from XML using ASP.NET C#
  • Edit or Update data in XML using ASP.NET C#
  • Search in XML document (Where clause)

Definition

According to Wikipedia definition of XML is

XML:

Extensible Markup Language (<b>XML</b>) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.

 

How to write  XML tags

As I told previously it is like HTML, a markup language, so its clear it will be written with the help of markup tags as we write HTML. Lets check a sample of XML.

<computer>
   <language>
     <id>1</id><title lang="en"></title>
     <author>Dennis Ritchie</author>
   </language>
   <language>
     <id>2</id><title></title>
     <author>Anders Hejlsberg</author>
   </language>
   <language>
     <id>3</id><title></title>
     <author>Yukihiro "Matz" Matsumoto</author>
   </language>
</computer> 

Its looks like a database...Where data are defined in a tree structure with child and sub child. The whole XML structure are like.

<root>
   <child>
     <subchild>...Data...</subchild>
   </child>
</root> 
<root>
   <child>
     <subchild>...Data...</subchild>
   </child>
</root> 
<root>
   <child>
     <subchild>...Data...</subchild>
   </child>
</root> 

Hope its clear how XML is organized to store data and perform. Now lets check next topic, write into XML using C#.

Create a XML file in .NET:

To write a XML file in ASP.NET using C# you need to add a new namespace

using System.Xml;

And one extra class named XmlWriter. Create an object of XmlWriter and using that object we will create a XML file and also write into it. How? Lets check the following code thoroughly.

Language[] lang= new Language[3];
employees[0] = new Employee(1, "C", "Dennis Ritchie");
employees[1] = new Employee(2, "C#", "Anders Hejlsberg");
employees[2] = new Employee(3, "Ruby", "Yukihiro "Matz" Matsumoto");

using (XmlWriter writer = XmlWriter.Create("ComLang.xml"))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("Computer");

    foreach Language lang1 in lang)
    {
        writer.WriteStartElement("Language");

 writer.WriteElementString("ID", employee.Id.ToString());
 writer.WriteElementString("title", employee.FirstName);
 writer.WriteElementString("author", employee.LastName);

 writer.WriteEndElement();
    }
 
    writer.WriteEndElement();
    writer.WriteEndDocument();
}

Read from a XML file

After creating a XML file now its time to show the data. To view data the best one is GridView. So we will use GridView here to show the data of a XML file. You can bind a GridView with a XML file by 2 methods. First one is little bit simpler using XMLDataSource. And second one is the greatest way to do....CODING... Smile | :) . No doubt I will show by second method. So, take a GridView and on the PageLoad method write down the following code.

<asp:gridview autogeneratecolumns="false" id="GridView1" runat="server">
    <columns>
        <asp:boundfield datafield="Id" headertext="Id">
        <asp:boundfield datafield="title" headertext="Title">
        <asp:boundfield datafield="author" headertext="Author">
    </columns>

C# code

using System.Data;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        fillGrid();
    }
}
 
private void fillGrid()
{
    using (DataSet ds = new DataSet())
    {
        ds.ReadXml(Server.MapPath("~/ComLang.xml"));
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

Creating and bindng is over. Its time to edit and update.

Edit or Update data in XML

We will edit a node of the XML file used. Lets assume we will change the author of language C. So how will code? Lets check.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("~/ComLang.xml"));

XmlNodeList nodeList = xmlDoc.SelectNodes("/computer/language");
// Chnange the author name of C to TextBox value
nodeList[0].ChildNodes[1].InnerText = txtAuhor.Text;
xmlDoc.Save(Server.MapPath("~/ComLang.xml"));
Response.Write("Succcessfully updated !");

nodeList[0].ChildNodes[1] means the second attribute of 1st node. A simple 2D matrix. So change it according to you attribute.

Search in XML document

Now in your mind one question may arise, here Arka has shown only by a particular attribute, what about the others, if I don't know at which position C language node is present. Remember we have taken a ID attribute with out node. We will use that one to edit or update. Lets check how to to do this. This is like Where clause in XML.

XDocument document = XDocument.Load(Server.MapPath("~/ComLang.xml"));

var q = from r in document.Descendants("Language") where (int)r.Element("ID") ="+ txtID.Text +" select new {
 Title = r.Element("title").Value, Author = r.Element("author").Value };

GridView1.DataSource = q;
GridView1.DataBind();

Now I hope its clear how to fetch a particular row of a XML document. I thing this post will clear the whole confusions about XML and how to use XML. If you still have some confusion don't hesitate to ask me any thing. That is all for this time....Practice yourself...Happy coding Smile | :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Arkadeep De
Software Developer Speed TechnoSolutions Pvt. Ltd.
India India
Visit my blog ASP With Arka @ http://asp-arka.blogspot.in
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141216.1 | Last Updated 6 Oct 2014
Article Copyright 2014 by Arkadeep De
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid