I have an existing XML file that I would like to append without changing the format. Existing File looks like this:
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 PreserveWhitespace
property (http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx).
You could try something like this...
string fileLocation = "clients.xml";
if (!File.Exists(fileLocation))
{
XmlTextWriter writer = new XmlTextWriter( fileLocation, null );
writer.WriteStartElement( "Clients" );
writer.WriteEndElement();
writer.Close();
}
// Load existing clients and add new
XElement xml = XElement.Load(fileLocation);
xml.Add(new XElement("User",
new XAttribute("username", loginName),
new XElement("DOB", dob),
new XElement("FirstName", firstName),
new XElement("LastName", lastName),
new XElement("Location", location)));
xml.Save(fileLocation);
That should get you started, just replace the variables with whatever you are using and dont forget to add the System.Xml.Linq namespace.
If youre still having problems post back here and well help you get through it.
If you want to use serialization (meaning you have a data object want to serialize in to XML and append to an existing XML file) you can use this generic method SerializeAppend<T>
. It does exactly what you need. I also added two more methods for anyone that may benefit
public static void Serialize<T>(T obj, string path)
{
var writer = new XmlSerializer(typeof(T));
using (var file = new StreamWriter(path))
{
writer.Serialize(file, obj);
}
}
public static T Deserialize<T>(string path)
{
var reader = new XmlSerializer(typeof(T));
using (var stream = new StreamReader(path))
{
return (T)reader.Deserialize(stream);
}
}
public static void SerializeAppend<T>(T obj, string path)
{
var writer = new XmlSerializer(typeof(T));
FileStream file = File.Open(path, FileMode.Append, FileAccess.Write);
writer.Serialize(file, obj);
file.Close();
}