Monday, April 25, 2011

Searching XML file using ASP.NET and C#

I have found how to search a particular element from the XML file.

The XML file is:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<company>
<employee id="109">
<fname>John</fname>
<lname>Graph</lname>
<age>28</age>
</employee>
<employee id="110">
<fname>Anna</fname>
<lname>Laoe</lname>
<age>32</age>
</employee>
<employee id="111">
<fname>Ashley</fname>
<lname>Kazzl</lname>
<age>34</age>
</employee>
<employee id="113">
<fname>Greg</fname>
<lname>Muray</lname>
<age>24</age>
</employee>
<employee id="114">
<fname>Fannie</fname>
<lname>Dow</lname>
<age>36</age>
</employee>
</company>

The code to search the particular employee record from the existing xml file is as follows:
(I don't know if this is a better way to search a XML file, so plz. help me in optimizing the code)


 string empid1 = Request.QueryString["empid"];
        Response.Write("<br>XML file searching using asp.net<br><br>");
        XmlDocument doc = new XmlDocument();

        string xmlFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/emp.xml");
        doc.Load(xmlFile);
      int  empid=int.Parse(empid1);// convert the empid1 to int

        XmlNodeList xmlnode = doc.GetElementsByTagName("employee");
        for (int i = 0; i < xmlnode.Count; i++)
        {
                      
                XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;
                if (int.Parse(xmlattrc[0].Value) == empid)
                {
                    Response.Write("<br>Employee-ID: " + xmlattrc[0].Value);
                    Response.Write("<br>First Name: " + xmlnode[i].ChildNodes[0].InnerText);
                    Response.Write("<br>Last Name: " + xmlnode[i].ChildNodes[1].InnerText);
                    Response.Write("<br>Age: " + xmlnode[i].ChildNodes[2].InnerText);
                    Response.Write("<br>");
                }
        }




Second Case 
----------------
I got the solution to Update the data for a Particular Node (in this case to update the data of particular Employee)
I am pasting the complete C# file of that page

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;

public partial class xml1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
//Page_Load will just grab the Employee-Id of particular Employee and will search for that EmployeeID in the XML file. If it find a appropriate match then it will
//display all the Details of that Employee viz. Empid(Empid is not editable), First Name(editable), Last Name(editable), Age(editable)
        if (!IsPostBack)
        {
            string empid1 = Request.QueryString["empid"];
            // Response.Write(empid1); WF
            //  Response.Write("<br>XML file searching using asp.net<br><br>");
            XmlDocument doc = new XmlDocument();

            string xmlFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/emp.xml");
            doc.Load(xmlFile);
            int empid = int.Parse(empid1);

            XmlNodeList xmlnode = doc.GetElementsByTagName("employee");
            for (int i = 0; i < xmlnode.Count; i++)
            {


                XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;
                if (int.Parse(xmlattrc[0].Value) == empid)
                {
                    lblEmpid.Text = xmlattrc[0].Value;
                    txtFirstName.Text = xmlnode[i].ChildNodes[0].InnerText; //Assign First Name from XML file to txtFirstName Text Box
                    txtLastName.Text = xmlnode[i].ChildNodes[1].InnerText; //Assign Last Name from XML file to txtLastName Text Box
                    txtAge.Text = xmlnode[i].ChildNodes[2].InnerText;// //Assign Age from XML file to txtAge Text Box
                 
                }
            }

        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //This Code will Update the XML file and will replace the data in the Xmlnode.
        // We can change the First Name, Last Name , Age of a PArticular Employee by using this code.
        string empid1 = lblEmpid.Text.ToString();
        XmlDocument doc = new XmlDocument();
        string fname = txtFirstName.Text;
        string lname = txtLastName.Text;
        string age = txtAge.Text;
        string xmlFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/emp.xml");
        doc.Load(xmlFile);
        int empid = int.Parse(empid1);

        XmlNodeList xmlnode = doc.GetElementsByTagName("employee");
        for (int i = 0; i < xmlnode.Count; i++)
        {


            XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;
            if (int.Parse(xmlattrc[0].Value) == empid)
            {
              
              
                xmlnode[i].ChildNodes[0].InnerText = fname;//ChildNodes[0] is First Name
                xmlnode[i].ChildNodes[1].InnerText = lname;
                xmlnode[i].ChildNodes[2].InnerText = age;
                doc.Save(xmlFile);// The New Data is Saved in the XML file by replacing old data for that particular employee.
            }
        }
    }
}


Case 3
--------
Instead of looping each employee for get a particular employee using ID, we can use XPath.
You can change the following code

XmlNodeList xmlnode = doc.GetElementsByTagName("employee");
        for (int i = 0; i < xmlnode.Count; i++)
        {


            XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;
            if (int.Parse(xmlattrc[0].Value) == empid)
            {
                
                
                xmlnode[i].ChildNodes[0].InnerText = fname;//ChildNodes[0] is First Name
                xmlnode[i].ChildNodes[1].InnerText = lname;
                xmlnode[i].ChildNodes[2].InnerText = age;
                doc.Save(xmlFile);// The New Data is Saved in the XML file by replacing old data for that particular employee.
            }
        }
 AS (Which uses XPath)
XmlNodeList xmlnode = doc.SelectNodes("//employee[@id=" + empid + "]");
        for (int i = 0; i < xmlnode.Count; i++)   // Loops only once if record exists
        {


            //XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;  //-- This Code is not needed
            //if (int.Parse(xmlattrc[0].Value) == empid) //-- This code is not needed
            //{
                
                
                xmlnode[i].ChildNodes[0].InnerText = fname;//ChildNodes[0] is First Name
                xmlnode[i].ChildNodes[1].InnerText = lname;
                xmlnode[i].ChildNodes[2].InnerText = age;
                doc.Save(xmlFile);// Even this line can be out of the for loop...
            //}
        }


CASE 3
---------
I got solution to add (append) an element to in the existing XML file at the end of file.
When I add the (employee) element to the end of the file , I search the last  empid and increment it by 1 and then insert this current empid in the empid attribute of the current employee (element) being added to the end of the file.
Limitations: I cannot see if there are any duplicates. (but this xml file does not contain any mission critical data).
I am pasting the code in this section (Please advice if I can write my code in a better way [:)])


 string fname, lname, age;
        fname = txtFirstName.Text.ToString();
        lname = txtLastName.Text.ToString();
        age = txtAge.Text.ToString();
        XmlDocument doc = new XmlDocument();
        string xmlFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/emp.xml");
        doc.Load(xmlFile);
        //First we have to get the empid of the last employee and increment it by 1 for the new employee
        XmlNodeList xmlnode = doc.GetElementsByTagName("employee");
        //Response.Write("<script type='text/javascript'>alert('" + xmlnode.Count + "')</javascript>");
        XmlNode empnode = doc.CreateElement("employee");
       // Response.Write(xmlnode.Count);//WF
     
      XmlAttributeCollection xmlattrc = xmlnode[xmlnode.Count-1].Attributes;

       //Response.Write(xmlattrc[0].Value);//WF
      
      
      
       int lastempid = int.Parse(xmlattrc[0].Value);//Get the Emp-Id of the last Employee
       int currempid = lastempid + 1;
         
        XmlNode empid = doc.CreateNode(XmlNodeType.Attribute, "id", "");
        empid.Value =  currempid.ToString();
     
        empnode.Attributes.SetNamedItem(empid);
        XmlNode empfname = doc.CreateElement("fname");
        empfname.InnerText = fname;
        empnode.AppendChild(empfname);
        XmlNode emplname = doc.CreateElement("lname");
        emplname.InnerText = lname;
        empnode.AppendChild(emplname);
        XmlNode empage = doc.CreateElement("age");
        empage.InnerText = age;
        empnode.AppendChild(empage);
         doc.DocumentElement.AppendChild(empnode);
         doc.Save(xmlFile);


/////////////////

The XML file after New data is added:

<?xml version="1.0" encoding="ISO-8859-1"?>
<company>
  <employee id="109">
    <fname>John</fname>
    <lname>Graph</lname>
    <age>28</age>
  </employee>
  <employee id="110">
    <fname>Anna</fname>
    <lname>Laoe</lname>
    <age>32</age>
  </employee>
  <employee id="111">
    <fname>Allan</fname>
    <lname>Woods</lname>
    <age>25</age>
  </employee>
  <employee id="113">
    <fname>Greg</fname>
    <lname>Muray</lname>
    <age>24</age>
  </employee>
  <employee id="114">
    <fname>Fannie</fname>
    <lname>Dow</lname>
    <age>36</age>
  </employee>
  <employee id="115">
    <fname>Hello</fname>
    <lname>World</lname>
    <age>11</age>
  </employee>
  <employee id="116">
    <fname>Hello</fname>
    <lname>World</lname>
    <age>11</age>
  </employee>
</company>

Still I have to write the code to delete a particular node (employee) from the XML File.

CASE 4
----
I found the Solution for deleting a particular node (employee). from the XML file :
the employee node is deleted by first getting its empid and then deleting all the information associated with that empid(like fname,lname,age)

Following is the code:

string fname, lname, age;
            fname = txtFirstName.Text.ToString();
            lname = txtLastName.Text.ToString();
            age = txtAge.Text.ToString();
            string empid1 =Request.Querystring["empid"]; // the empid is passed in the querystring
            XmlDocument doc = new XmlDocument();
            string xmlFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/emp.xml");
            doc.Load(xmlFile);
            int empid = int.Parse(empid1);
            XmlNode deletenode = doc.SelectSingleNode("//employee[@id=" + empid + "]");
            deletenode.ParentNode.RemoveChild(deletenode); //In this line all the information (i.e. child node) of employee are deleted.
            doc.Save(xmlFile);
(Please suggest if I can do the same thing in a better manner)

http://forums.asp.net/t/1318271.aspx/1

No comments:

Post a Comment