Search This Blog

Friday, October 28, 2011

Adding new Nodes to XML File in C#

1.Create a Dummy xml file with the name Patients.xml in your solution explorer.
    Ex:
 <Patients>
  <Patient type="IP">
    <VistorNum>134</VistorNum>
    <FName>Maha</FName>
    <LName>Veer</LName>
    <Age>89</Age>
    <Sex>Male</Sex>
  </Patient>
</Patients>
 
2.Create the UI to accept data from users.(Write the below code in .aspx page)
   VisitorNum:<asp:TextBox ID="tbVstrNum" runat="server" ></asp:TextBox><br />
    FName:<asp:TextBox ID="tbFName" runat="server" ></asp:TextBox><br />
    LName:<asp:TextBox ID="tbLName" runat="server" ></asp:TextBox><br />
    Age:<asp:TextBox ID="tbAge" runat="server" ></asp:TextBox><br />
    Sex:<asp:TextBox ID="tbSex" runat="server" ></asp:TextBox><br />
    <asp:Button ID="btnInsertPat" Text="AddPatient" runat="server" 
            onclick="btnInsertPat_Click" />
3.Write the below code in code behind's button click method.
    protected void btnInsertPat_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("Patients.xml"));
        //Create a New patient node.
        XmlNode nPatient=doc.CreateNode(XmlNodeType.Element,"Patient",null);
        //Create visitornUm,FName,LName,Age,Sex nodes and add 
        //it to Patient Node
        XmlElement eVistNum= doc.CreateElement("VistorNum");
        eVistNum.InnerText = tbVstrNum.Text;
        XmlElement eFName = doc.CreateElement("FName");
        eFName.InnerText = tbFName.Text;
        XmlElement eLName = doc.CreateElement("LName");
        eLName.InnerText = tbLName.Text;
        XmlElement eAge = doc.CreateElement("Age");
        eAge.InnerText = tbAge.Text;
        XmlElement eSex = doc.CreateElement("Sex");
        eSex.InnerText = tbSex.Text;
        nPatient.AppendChild(eVistNum);
        nPatient.AppendChild(eFName);
        nPatient.AppendChild(eLName);
        nPatient.AppendChild(eAge);
        nPatient.AppendChild(eSex);
        //Get the Root Patients Node ref.
        XmlNode root=doc.SelectSingleNode("Patients");
        //Add New patient node to root patient node.
        root.AppendChild(nPatient);
        string sPath = Server.MapPath("Patients.xml");
        doc.Save(sPath);
        //elem.AppendChild(
    }
Sign Up for dot net training course