Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with XML Records and DataGrid with C# and ASP.NET

In this article you will learn how to Read/Write the XML, Add XML Node / Record, Delete XML Node / Record and Display XML Data in DataGrid .

XML stand for Extensible markup language, The XML saved in a text file with extension .xml. By using the XML document you can save and retrieve date without using any database. Also XML is platform independent, so you can use the same XML with .NET and JAVA.

Application First Look - Data in XML

Figure 1: Application First Look - Data in XML

XML Data:

Let’s take a sample data to demonstrate the XML operations. This is a list of movies and their attributes.

Listing 1: XML Data

<?xml version="1.0" encoding="utf-8" ?>
<Movies>
  <Movie>
    <ID>1</ID>
    <Title>The Avengers</Title>
    <Director>Joss Whedon</Director>
    <Year>2012</Year>
    <Rating>8.7</Rating>
  </Movie>
  <Movie>
    <ID>2</ID>
    <Title>Dark Shadows</Title>
    <Director>Tim Burton</Director>
    <Year>2012</Year>
    <Rating>6.6</Rating>
  </Movie>
  <Movie>
    <ID>3</ID>
    <Title>Men in Black III</Title>
    <Director>Barry Sonnenfeld</Director>
    <Year>2012</Year>
    <Rating>NA</Rating>
  </Movie>
 </Movies> 

Now let’s go through the ASP.NET and C# code and understand that how to work with XML.

The below is ASP.NET Code which have the following components

  1. 5 textbox for Movie ID, Movie Title, Movie Director, Movie Year and Movie Rating.
  2. Two buttons for Add Movie and Remove Movie.
  3. A DataGrid to Display Movie list.

ASP.NET Code:

Listing 2: ASP.NET Script

<head runat="server">
    <title>MrBool.com ASP.NET and C# Tutorials</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Movie ID:
                </td>
                <td>
                    <asp:TextBox ID="txtMovieID" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Movie Title:
                </td>
                <td>
                    <asp:TextBox ID="txtMovieTitle" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Movie Director:
                </td>
                <td>
                    <asp:TextBox ID="txtMovieDirector" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Movie Year:
                </td>
                <td>
                    <asp:TextBox ID="txtMovieYear" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Movie Rating:
                </td>
                <td>
                    <asp:TextBox ID="txtMovieRating" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                </td>
            </tr>
        </table>
        <br />
        <asp:Button ID="btnAddMovie" runat="server" Text="Add Movie" OnClick="btnAddMovie_Click" />
        <asp:Button ID="btnRemoveMovie" runat="server" Text="Remove Movie" OnClick="btnRemoveMovie_Click" />
        <br />
        <br />
        <br />
        <asp:DataGrid ID="dgData" runat="server" AutoGenerateColumns="true">
            <HeaderStyle Font-Bold="true" />
        </asp:DataGrid>
        <br />
    </div>
    </form>
</body>

C# Code:

Before proceeding to main operations, let’s first talk about the reading and writing of XML file. “GetXMLDataSet” method read the XML file and returns the data in DataSet format. ReadXml is the method to read the data, which accepts the local file path as an input. This is a web application so we have to use Server.MapPath method to convert relative or virtual path to physical path.

Listing 3: GetXMLDataSet

private DataSet GetXMLDataSet()
    {
        DataSet objDS = new DataSet();

        objDS.ReadXml(Server.MapPath(strXMLFileName));
        return objDS;
    }

The ReadXML method read the XML file and returns the object of XmlDocument.

Listing 4: ReadXML

private XmlDocument ReadXML()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(Server.MapPath(strXMLFileName));
        return xmlDoc;
    }

WriteXML method takes the XmlDocument object and writes to XML file.

Listing 5: WriteXML

private void WriteXML(XmlDocument objDoc)
    {
        objDoc.Save(Server.MapPath(strXMLFileName));
    }

DisplayMovies method takes XML content as dataset and adds the movie list to DateGrid. First assign the dataset into DataGrid and then bind the grid.

Listing 6: Assign Dataset and bind

dgData.DataSource = oDs;
dgData.DataBind();

Listing 7: DisplayMovies

private void DisplayMovies()
    {
        DataSet oDs = GetXMLDataSet();
        if (oDs != null && oDs.Tables.Count > 0 && oDs.Tables[0].Rows.Count > 0)
        {
            dgData.DataSource = oDs;
            dgData.DataBind();
        }
    }

ADD XML Element:

So let’s start with adding a new element and inner elements.

Movie Added - The Godfather

Figure 2: Movie Added - The Godfather

The btnAddMovie_Click is taking the input from all textboxes and will add to XML document. First read the XMl data in XmlDocument object. Now create a “Movie” element

Listing 8: Creating Movie Element

XmlElement objElement = objXMLDoc.CreateElement("Movie");

Now create all inner elements and assign value from textbox.

Listing 9: Creating Inner Elements and assign value from textbox

XmlElement ID = objXMLDoc.CreateElement("ID");
ID.InnerText = txtMovieID.Text; 

Now add the inner elements to Movie element

Listing 10: Add Inner Elements

objElement.AppendChild(ID);

Once you added all inner elements to Movie element, add the movie element to XmlDocument

Listing 11 : Add Movie Element

objXMLDoc.DocumentElement.AppendChild(objElement); 

Save the XMl Document and Redisplay the DataGrid.

Listing 12: Add Movies

protected void btnAddMovie_Click(object sender, EventArgs e)
    {
        XmlDocument objXMLDoc = ReadXML();

        XmlElement objElement = objXMLDoc.CreateElement("Movie");
        XmlElement ID = objXMLDoc.CreateElement("ID");
        ID.InnerText = txtMovieID.Text;
        XmlElement Title = objXMLDoc.CreateElement("Title");
        Title.InnerText = txtMovieTitle.Text;
        XmlElement Director = objXMLDoc.CreateElement("Director");
        Director.InnerText = txtMovieDirector.Text;
        XmlElement Year = objXMLDoc.CreateElement("Year");
        Year.InnerText = txtMovieYear.Text;
        XmlElement Rating = objXMLDoc.CreateElement("Rating");
        Rating.InnerText = txtMovieRating.Text;

        objElement.AppendChild(ID);
        objElement.AppendChild(Title);
        objElement.AppendChild(Director);
        objElement.AppendChild(Year);
        objElement.AppendChild(Rating);

        objXMLDoc.DocumentElement.AppendChild(objElement);
        //Save XML
        WriteXML(objXMLDoc);

        //Display Movie List again
        DisplayMovies();

    }

Remove XML Element:

After Adding an element let’s talk about deleting an element. To delete a Node you have to loop through all movies and then all then inner elements of the movie. Because suppose you have to delete a movie by target, so have to go each inner title and then delete the parent node.

Movie Deleted - Men in Black

Figure 3: Movie Deleted - Men in Black |||

First get the list of movies and then loop through all the movies:

Listing 13: Getting the List of Movies

XmlNodeList lstMovies = objXMLDoc.GetElementsByTagName("Movie"); 
foreach (XmlNode objNode in lstMovies)

Now get the child of each movie and loop through it:

Listing 14: Getting the child of each movie

XmlNodeList objNodeList = objNode.ChildNodes; 
foreach (XmlNode objInnerNode in objNodeList)

Now check if inner node has the similar movie title.

Listing 15: Checking Similar Movie

if (objInnerNode.InnerText == txtMovieTitle.Text.ToString())

Once result match just exit from both the loops and delete the element.

Listing 16: Delete the element

objXMLDoc.DocumentElement.RemoveChild(objNode); 

Now Save the XmlDocument and display the movie list again.

Listing 17: Remove Movies

protected void btnRemoveMovie_Click(object sender, EventArgs e)
    {
        bool blnFlag = false;
        XmlDocument objXMLDoc = ReadXML();

        XmlNodeList lstMovies = objXMLDoc.GetElementsByTagName("Movie");

        foreach (XmlNode objNode in lstMovies)
        {
            XmlNodeList objNodeList = objNode.ChildNodes;

            foreach (XmlNode objInnerNode in objNodeList)
            {                
                if (objInnerNode.InnerText == txtMovieTitle.Text.ToString())
                {
                    objXMLDoc.DocumentElement.RemoveChild(objNode);

                    blnFlag = true;
                    break;
                }
            }
            if (blnFlag)
                break;
        }
        //Save XML
        WriteXML(objXMLDoc);

        //Display Movie List again
        DisplayMovies();

    }  
 


I am having total 7+ years of experience in developing applications using C#, VB.NET, ASP.NET, Silverlight, WCF, SQL Server and Oracle. I am holding a M.Tech degree in Intelligent systems. For more information, visit my Linkedin p...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login