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.
You should use the XmlDocument class to load the whole file, modify it in memory and then write the contents back replacing the original file. Don’t worry, it won’t mess up your markup, and you can even ask it to preserve non-significant whitespace in the original document using the
PreserveWhitespaceproperty (http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx).