tags:

views:

132

answers:

3

I have a Windows Forms application which contain a textbox (tbox) and two buttons: Save (b1) and Delete (b2) and an XML file leaf.xml

Whenever i am putting anything in textbox and then click Save (b1) the content in textbox will be saved in the leaf.xml file. When i press delete (b2), it will delete from the file leaf.xml and at the same time it will disable the Save button.

this is the xml file wahatever adding will come to tag,suppose if we add test it will come as

<Name>test</Name>

+4  A: 

You probably want to look at the XMLSerializer. It will let you serialize/deserialize your "ObjectClass" to/from a stream. Likewise, you probably want to look at the File class, for opening file streams (to pass into the XMLSerializer) and delete files (File.Delete).

Brian Genisio
A: 

The save should be something like this, the delete works with XPath (find the Name element that has the supplied text in it, then delete it, save the file again.)

This will not work if any person with the same name is entered off course...

Save_Click(object sender, EventArgs e)
{
  FileStream fs = new FileStream("leaf.xml",FileMode.Open,FileAccess.Read, FileShare.ReadWrite);
  XmlDocument doc = new XmlDocument();
  doc.Load(fs);
  XmlElement elem = doc.CreateElement("","Name","");
  XmlText text = doc.CreateTextNode(textbox1.Text);
  elem.AppendChild(text);
  doc.RootNode.AppendChild(elem);

  doc.Save("leaf.xml");
}
Colin
Sorry... Nobody should ever be using the XmlDocument for this type of work unless they are working on legacy code. There are so many other ways to do this, and the XmlDocument is the worst for many reasons. At least use the XDocument in place of the XmlDocument...
Brian Genisio
I agree, this is something I wrote down to point the OP in a direction. He is clearly new at this...
Colin
i am getting this error 'System.Xml.XmlDocument' does not contain a definition for 'RootNode'
peter
sorry, it should be FirstChild
Colin
A: 

Use LINQ to do that....see code below:

XDocument xmlDoc = XDocument.Load(Server.MapPath("People.xml"));

xmlDoc.Element("Persons").Add(new XElement("Person", new XElement("Name", txtName.Text),
new XElement("City", txtCity.Text), new XElement("Age", txtAge.Text)));

xmlDoc.Save(Server.MapPath("People.xml"));
lblStatus.Text = "Data successfully added to XML file.";
Bhaskar