Appending an existing XML file with c#
Posted
by Farstucker
on Stack Overflow
See other posts from Stack Overflow
or by Farstucker
Published on 2010-04-15T13:04:14Z
Indexed on
2010/04/16
3:33 UTC
Read the original article
Hit count: 228
I have an existing XML file that I would like to append without changing the format. Existing File looks like this:
<Clients>
<User username="farstucker">
<UserID>1</UserID>
<DOB />
<FirstName>Steve</FirstName>
<LastName>Lawrence</LastName>
<Location>NYC</Location>
</User>
</Clients>
How can I add another user using this format? My existing code is:
string fileLocation = "clients.xml";
XmlTextWriter writer;
if (!File.Exists(fileLocation))
{
writer = new XmlTextWriter(fileLocation, null);
writer.WriteStartDocument();
// Write the Root Element
writer.WriteStartElement("Clients");
// End Element and Close
writer.WriteEndElement();
writer.Close();
}
// Append new data here
Ive thought about using XmlDocument Fragment to append the data but Im not certain if I can maintain the existing format ( and empty tags ) without messing up the file.
Any advice you could give is much appreciated.
EDIT Ive changed the code to read the original XML but the file keeps getting overwritten.
© Stack Overflow or respective owner