Saturday, October 4, 2014

XML and .NET

XML - Extensible Markup Language is a markup language like HTML designed for describing data as a database.

Topics to discuss :
  • Definition
  • How to write tags XML
  • 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 of XML :

According to Wikipedia definition of XML is.
Extensible Markup Language (XML) 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 tags in XML :

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.


   
     1
     C
     Dennis Ritchie
   
   
     2
     C#
     Anders Hejlsberg
   
   
     3
     Ruby
     Yukihiro "Matz" Matsumoto
   
 

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

   
     ...Data...
   
 

   
     ...Data...
   
 

   
     ...Data...
   
 

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... :). No doubt I will show by second method.

So, take a GridView and on the PageLoad method write down the following code.


    
        
        
        
    


Now the 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 :)

1 comment:

  1. Great job Arka!

    I replaced:
    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");

    with an arraylist:
    List Books = new List();
    myBook newBook = new myBook(1, "C", "Dennis Ritchie");
    Books.Add(newBook);
    newBook = new myBook(2, "C#", "Anders Hejlsberg");
    Books.Add(newBook);
    newBook = new myBook(3, "Ruby", "Matsumoto");
    Books.Add(newBook);

    It was easier for me to understand. I didn't know where 'Language' or 'Employees' came from. I had to create a small class called myBook.

    Thanks for the help.

    ReplyDelete

Popular Posts

Pageviews