Chris Rutherford
Chris Rutherford

Reputation: 1672

XDocument adding new document declaration to XML File

So I have this block of code that is part of an If/Else that if the file being written to already exists, it should append to the document. However it appears to be adding a new xml declaration and root element as if it's a new file. The code looks like this:

  {
     FileStream fs = new FileStream(configFile, FileMode.Open);
     XDocument xD = XDocument.Load(fs);
     XElement root = xD.Element("Store");
     root.Add(
          new XElement("template", new XElement("filePath", tmp.TempPath),
          new XElement("Name", tmp.TempName),
          new XElement("description", tmp.TempDesc)));
     xD.Save(fs);
     fs.Flush();
     fs.Dispose();
 }

On the second pass of this block, it errors out stating there is an invalid xml declaration in the middle of the file..... which looks like this:

<?xml version="1.0" encoding="utf-8"?>
<Store>
  <template>
    <filePath>.\templates\balls.html</filePath>
    <Name>Balls</Name>
    <description>Benoit</description>
  </template>
</Store><?xml version="1.0" encoding="utf-8"?>
<Store>
  <template>
    <filePath>.\templates\balls.html</filePath>
    <Name>Balls</Name>
    <description>Benoit</description>
  </template>
  <template>
    <filePath>.\templates\benoit.html</filePath>
    <Name>benoit</Name>
    <description>balls</description>
  </template>
</Store>

I have a sneaking suspicion that I'm not using LINQ correctly for XML.

Upvotes: 1

Views: 349

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

You are appending XML to the same file instead of overwriting the file.

Option to fix:

  • seek file back to the beginning
  • re-open file

     // load and close stream  
     XDocument xD;
     using(var fs = new FileStream(configFile, FileMode.Open))
     {
        xD = XDocument.Load(fs);
     }
    
     // modify document
     XElement root = xD.Element("Store");
     root.Add(
          new XElement("template", new XElement("filePath", tmp.TempPath),
          new XElement("Name", tmp.TempName),
          new XElement("description", tmp.TempDesc)));
    
     // open stream again and save XML
     using(var fs = new FileStream(configFile, FileMode.Open))
     {
        xD.Save(fs);
     }
    

Upvotes: 2

Related Questions