When you only need to extract XML data from a database, you can make a native XML database. In this tutorial, you will learn how to operate XML data in Visual C#.

Setup

If you have not already done so, open Visual Studio and set up a new web project OR download the source files located at the end of the tutorial. 

We used over 10 web hosting companies before we found Server Intellect. They offer dedicated servers, and they now offer cloud hosting!

The Concept…

Microsoft .NET introduces a suite of XML APIs built on industry standards such as DOM, XPath, XSD, and XSLT. The .NET Framework XML classes also offer convenience, better performance, and a more familiar programming model, tightly coupled with the .NET data access APIs—ADO .NET.

The XmlWriter, XmlReader, and XmlNavigator classes and classes that derive from them include the XMLTextReader and XMLTextWriter. These classes encapsulate a number of functionalities that previously had to be accomplished manually.

Step one.

We will begin by making our user interface. Within a fieldset, we will have a Gridview, the ability to select, cancel, edit, modify and insert as well with the command field control. You may copy and paste the following code into your default.aspx page.
Code Block
Default.aspx

<fieldset style="height: 401px"> 
<legend>Operate Xml</legend
>
author:&nbsp;<asp:TextBox ID="TextBox1" runat="server" Width="231px"></asp:TextBox><br 
/>
title: &nbsp; &nbsp;&nbsp;<asp:TextBox ID="TextBox2" runat="server" Width="231px"></asp:TextBox><br 
/>
content:<asp:TextBox ID="TextBox3" runat="server" Width="231px"></asp:TextBox><br 
/>
<
asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add" 
/>
<
asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="modify" 
/>
<
asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Delete" 
/>
<
asp:Button ID="Button4" runat="server" OnClick="Button4_Click" Text="Clear" /><br /><br 
/>
 
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Width="428px" AutoGenerateColumns="False">
 
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" 
/>
<
Columns
>
<
asp:CommandField CancelText="Cancel" DeleteText="Delete" EditText="Modify" InsertText="Insert" NewText="New" SelectText="Select" ShowSelectButton="True" UpdateText="Update" 
/>
<
asp:BoundField DataField="author" HeaderText="Author" 
/>
<
asp:BoundField DataField="title" HeaderText="Title" 
/>
<
asp:BoundField DataField="content" HeaderText="Content" 
/>
</
Columns
>
<
RowStyle BackColor="#E3EAEB" 
/>
<
EditRowStyle BackColor="#7C6F57" 
/>
<
SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" 
/>
<
PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" 
/>
<
HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" 
/>
<
AlternatingRowStyle BackColor="White" 
/>
</
asp:GridView
>
</
fieldset>


Save and switch over to design or split view. You will notice that you now have a user interface that will allow you to select a listed item and modify, add or delete it in any way.

We also added four buttons to the web page and the back end. Which as you saw, were Add, modify, Delete and Clear.

Step two.

In order for the buttons and the connection to work, we will need to add some code to our code behind. We will then add 2 functions to include loadXmlData and FindXmlData. Copy and paste the following code into your code behind.
Code Block
Default.aspx.cs

protected void Button1_Click(object sender, EventArgs e)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
         XmlElement newelement = xmldoc.CreateElement("poems");
        XmlElement xmlAuthor = xmldoc.CreateElement("author");
        XmlElement xmlTitle = xmldoc.CreateElement("title");
        XmlElement xmlContent = xmldoc.CreateElement("content");
 
        xmlAuthor.InnerText = this.TextBox1.Text.Trim();
        xmlTitle.InnerText = this.TextBox2.Text.Trim();
        xmlContent.InnerText = this.TextBox3.Text.Trim();
 
        newelement.AppendChild(xmlAuthor);
        newelement.AppendChild(xmlTitle);
        newelement.AppendChild(xmlContent);
 
        xmldoc.DocumentElement.AppendChild(newelement);
 

         xmldoc.Save(Server.MapPath(@"App_Data\smallfools.xml"));
 
        loadXmlData();
    }
     protected void Button2_Click(object sender, EventArgs e)
    {
        if (selectIndex == -1)
        {
            this.RegisterClientScriptBlock("alertmessage""<script>alert('please select one modify data item.')</script>");
        }
        
else
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
            XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(selectIndex);
 
            xmlnode["author"].InnerText = this.TextBox1.Text.Trim();
            xmlnode["title"].InnerText = this.TextBox2.Text.Trim();
            xmlnode["content"].InnerText = this.TextBox3.Text.Trim();
 
            xmldoc.Save(Server.MapPath(@"App_Data\smallfools.xml"));
 
            loadXmlData();
        }
    }
 
     protected void Button3_Click(object sender, EventArgs e)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
        XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(selectIndex);
        xmlnode.ParentNode.RemoveChild(xmlnode);
        xmldoc.Save(Server.MapPath(@"App_Data\smallfools.xml"));
 
        loadXmlData();
        this.TextBox1.Text = "";
        this.TextBox2.Text = "";
        this.TextBox3.Text = "";
    }
     protected void Button4_Click(object sender, EventArgs e)
    {
        this.TextBox1.Text = "";
        this.TextBox2.Text = "";
        this.TextBox3.Text = "";
    }
 
     private void loadXmlData()
    {
        DataSet myDs = new DataSet();
        myDs.ReadXml(Server.MapPath(@"App_Data\smallfools.xml"));
 
        if (myDs.Tables.Count > 0)
        {
            this.GridView1.DataSource = myDs;
            this.GridView1.DataBind();
        }
    }

    private void FindXmlData(int selectedIndex)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
        XmlNodeList xmlnodelist = xmldoc.DocumentElement.ChildNodes;
        XmlNode xmlnode = xmlnodelist.Item(selectedIndex);
        this.TextBox1.Text = xmlnode["author"].InnerText;
        this.TextBox2.Text = xmlnode["title"].InnerText;
        this.TextBox3.Text = xmlnode["content"].InnerText;
    }
     protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        selectIndex = this.GridView1.SelectedIndex;
        FindXmlData(selectIndex);
    } 
}


I just signed up at Server Intellect and couldn’t be more pleased with my fully scalable & redundant cloud hosting! Check it out and see for yourself.

On our page load method, we initialize the xml texts to the appropriate xml children elements and save everything for the XML document and load the data from that document to the page. The button onclick events are set to register all data entered or needed to be removed and modify the text to match the entry options, save the XML document and call the loadXmlData() method and that loads the data on the page.

Our FindXMLData() method retrieves the information from the selected item from the gridview and present them in the text box. Our actual GridView method initializes the selectIndex to whatever is selected and calls the FindXmlData() method.

The final product will appear like the image below:



A Few Last Words…

Learning SQL in ASP.NET is easy and we intend to be there to assist you every step of the way. Join us next time for additional database tutorials.