0

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>
marto31
  • 21
  • 3
  • are you wanting to append the data if it the file is present? – Mark Hall Jul 03 '14 at 22:39
  • XDocument and XmlWriter, this is not the same technology, and my question is about XmlWriter. [best-way-to-build-xml](http://stackoverflow.com/questions/284324/what-is-the-best-way-to-build-xml-in-c-sharp-code) – marto31 Jul 04 '14 at 08:06

1 Answers1

0

I'm not sure why you'd want to do this; however, you can create a filestream, and then feed the file stream into this overload http://msdn.microsoft.com/en-us/library/x972ksd0.aspx of XmlWriter.Create

I don't have an IDE but off the top of my head it'd look something like this:

   using(FileStream s = new FileStream("file.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite))
   using (XmlWriter writer = XmlWriter.Create(s))
    {
      writer.WriteStartDocument();
      // ...
      writer.WriteEndDocument();
    }
Aelphaeis
  • 2,593
  • 3
  • 24
  • 42