Click to See Complete Forum and Search --> : how to add new item to XML


Panda2001
May 7th, 2003, 09:54 AM
Hi,

I have a ListBox, and I can successfully display my XML data into a listbox using the below code:
try
{
doc.Load ("..\\..\\StockList.xml");
XmlNodeList nodeLst = doc.GetElementsByTagName ("Stock");

foreach (XmlNode node in nodeLst)
StockListBox.Items.Add (node.InnerText);
}
catch (Exception)
{}

NOW, I would like to add item to the XML file programmatically. Here's what I have so far, but it does not work (screwed up my XML file by deleting everything !)
StockListBox.Items.Add (txtbox_Symbol.Text);

try
{
XmlNode newNode = doc.CreateElement ("Stock", txtbox_Symbol.Text, null);
XmlTextWriter tr = new XmlTextWriter("..\\..\\StockList.xml",null);
tr.Formatting = Formatting.Indented;
doc.WriteContentTo (tr);
}

Btw, the XML file is in the below format:
<?xml version 2.0>
<StockList>
<Stock>ABC</Stock>
<Stock>DEF</Stock>
<Stock>GHI</Stock>
</StockList>

PLEASE.... HELP ME... (Btw, it will be a great idea if someone can suggest a faster way to bind/Add data to ListBox)

Panda ~_~

Sinisha Ristich
May 7th, 2003, 03:36 PM
What's wrong with the XML it looks fine to me?

Panda2001
May 9th, 2003, 09:30 AM
The XML is fine.
But when I try to update the XML, the XML will be corrupted/screwed.

btw, the variable "doc" is a XMLDocument object.

Panda