I would use XmlWriter without overwriting the file every time and write data following the existing tree..
XmlWriterSettings reglages = new XmlWriterSettings();
reglages.Indent = true;
using (XmlWriter writer = XmlWriter.Create("historique.xml", reglages))
{
writer.WriteStartDocument();
// ...
writer.WriteEndDocument();
}
EDIT : My solution with XmlDocument (not with XDocument)
XmlDocument DocXml = new XmlDocument();
XmlNode body;
if (File.Exists("file.xml"))
{
DocXml.Load("file.xml");
body = DocXml.SelectSingleNode("body");
}
else
{
XmlDeclaration xmlDeclaration = DocXml.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = DocXml.DocumentElement;
DocXml.InsertBefore(xmlDeclaration, root);
body = DocXml.CreateElement("body");
DocXml.AppendChild(body);
}
XmlNode ele1 = DocXml.CreateElement("ele1 ");
body.AppendChild( ele1 );
XmlNode ele2 = DocXml.CreateElement("ele2");
ele2.InnerText = "Text ele2";
ele1.AppendChild(ele2);
DocXml.Save("file.xml");
First use (file creation) :
<?xml version="1.0" encoding="UTF-8"?>
<body>
<ele1>
<ele2>Text ele2</ele2>
</ele1>
</body>
Other use (file modification) :
<?xml version="1.0" encoding="UTF-8"?>
<body>
<ele1>
<ele2>Text ele2</ele2>
</ele1>
<ele1>
<ele2>Text ele2</ele2>
</ele1>
</body>