Update a xml doc using windows forms and C# HELP!

B

BJ Allmon

I'm new to the .NET community. My name is BJ and I've been
developing web applications for years now. I'm very new
to .NET and could use some assistance. I don't think I'm
asking for very much here. This should be very common but
I haven't been able to find any concrete examples.
I'm creating a Windows Forms client/server application.
It's for sales staff and the client piece needs to store
to xml (preferrably). I know that windows programming
lends itself to this type of functionality but I have to
say I'm at a loss when it comes to finding out how to make
it work right.
I have a customer form page in the app that the user can
fill out. When the user clicks the save button I use an
event driven method that will write the form data to xml.
In the form of:
<Contacts>
<contact name="clientName" date="mm/dd/yyyy" />
</Contacts>
The problem is everytime I use the form it just appends
the same format to my xml document like so:
<Contacts>
<contact name="clientName" date="mm/dd/yyyy" />
</Contacts><Contacts>
<contact name="clientName" date="mm/dd/yyyy" />
</Contacts>
This makes it unreadable.
QUESTION: How do I make the child elements append inside
the root "Contacts"?
Here's my current code that causes the problem.

//Code snippet starts here.....
System.Xml.XmlDocument salesText = new XmlDocument();
XmlElement newContacts =
salesText.CreateElement("Contacts");
XmlElement newContact =
salesText.CreateElement("Contact");
salesText.AppendChild(newContacts);
newContacts.AppendChild
(newContact);
//Create a new XmlAttribute
XmlAttribute idAttribute =
salesText.CreateAttribute("Client");
idAttribute.Value =
this.textBox1.Text;
//Set the Attribute on the
XmlElement
newContact.SetAttributeNode
(idAttribute);
//Date Attribute
XmlAttribute dateAttribute =
salesText.CreateAttribute("Date");
dateAttribute.Value =
this.textBox2.Text;
newContact.SetAttributeNode
(dateAttribute);

//Insert the newly created
XmlElement into the XmlDocument
salesText.InsertAfter
(newContacts,salesText.LastChild);

//Create a FileStream and Save the
Document
FileStream docOut =
new FileStream
(docPath,FileMode.Append,FileAccess.Write,FileShare.ReadWri
te);
salesText.Save(docOut);
//code snippet ends here.

Any help much appreciated...
 
N

Nick Malik

In your code snippet, you are using FileMode.Append. This is what is
causing your output file to become invalid XML.
FileStream docOut = new FileStream(docPath,FileMode.Append,FileAccess.Write,FileShare.ReadWrite);
salesText.Save(docOut);

Change the first line above to FileMode.Create or FileMode.Write

HTH,
--- Nick
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top