Showing posts with label Xml Operation. Show all posts
Showing posts with label Xml Operation. Show all posts

Thursday, 9 February 2012

XML FILE OPERATIONS : UPDATE AND DELETE IN XML FILE



XML File Operations : Update a node in XML file

protected void UpdateXMLNode(string xmlFilePath)
        {
        if (File.Exists(xmlFilePath))
        {
            DataSet ds = new DataSet();
            ds.ReadXml(xmlFilePath);
            string filterExpression = "NAME = '" + TextBox1.Text + "'";
            DataRow[] row = ds.Tables[0].Select(filterExpression);
         if (row.Length == 1)
         {
             row[0][0] = TextBox2.Text;
             row[0][1] = TextBox3.Text;
             row[0][2] = TextBox4.Text;
            ds.WriteXml(xmlFilePath);
          }
          }
          }


XML File Operations : Delete from XML file

protected void DeleteXMLNode(string xmlFilePath)
        {
        if (File.Exists(xmlFilePath))
        {
            DataSet ds = new DataSet();
            ds.ReadXml(xmlFilePath);
            string filterExpression = "NAME = '" + TextBox4.Text + "'";
            DataRow[] row = ds.Tables[0].Select(filterExpression);
            if (row.Length == 1)
         {
            row[0].Delete();
            ds.WriteXml(xmlFilePath);
          }
          }
          }




XML FILE OPERATIONS : CREATE AND INSERT IN XML FILE



protected void InsertXML(string xmlFilePath, string elements, string element)
{
 if (!File.Exists(xmlFilePath))
{
string data = "<" + elements + ">" + "</" + elements + ">";
doc.Load(new StringReader(data));
XmlElement child = doc.CreateElement(element);
child.SetAttribute("NAME", TextBox1.Text);
child.SetAttribute("CITY", TextBox2.Text);
child.SetAttribute("NUMBER", TextBox3.Text);
doc.DocumentElement.AppendChild(child);
doc.Save(xmlFilePath);
         
}
else
{
doc.Load(xmlFilePath);
XmlElement child = doc.CreateElement(element);
child.SetAttribute("NAME", TextBox1.Text);
child.SetAttribute("CITY", TextBox2.Text);
child.SetAttribute("NUMBER", TextBox3.Text);
doc.DocumentElement.AppendChild(child);
doc.Save(xmlFilePath);
}
            }