JelleKerkstra
JelleKerkstra

Reputation: 512

Incorrect structured XML document after deleting element

When I try to load a XML file after deleting an Element from the file, it shows the following error: Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Line 9, position 10. What is wrong with my code?

This is my XML file:

<?xml version="1.0" encoding="UTF-8"?>
<data>
   <booze>booze1</booze>
   <booze>booze2</booze>
   <booze>booze3</booze>
   <booze>booze4</booze>
</data>

And my code:

using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("favorites.xml", FileMode.Open, file))
   {
       XDocument xDoc = XDocument.Load(stream, LoadOptions.None);
       // delete node
       xDoc.Descendants("data").Elements("booze").Where(x => x.Value == favorite).DescendantsAndSelf().Remove();
       xDoc.Save(stream);
    }
}

Upvotes: 1

Views: 158

Answers (1)

Nitkov
Nitkov

Reputation: 468

My guess is that when you run the code for the first time, the delete succeeds and your XDoc contains : <?xml version="1.0" encoding="utf-8"?> <data> <booze>booze1</booze> <booze>booze2</booze> <booze>booze4</booze> </data>

, but when calling XDoc.Save you simply append this to the favorites.xml file. After that, the favorites.xml file contains something like this:

<?xml version="1.0" encoding="UTF-8"?>
<data>
   <booze>booze1</booze>
   <booze>booze2</booze>
   <booze>booze3</booze>
   <booze>booze4</booze>
</data><?xml version="1.0" encoding="utf-8"?>
<data>
  <booze>booze1</booze>
  <booze>booze2</booze>
  <booze>booze4</booze>
</data>

That is why all the subsequent file loads throw the error. What you should do is overwrite the file, and not append to it. The first way of doing that that comes to mind is to close the stream, open it with Mode.Truncate and then save the XDoc. Or you can delete and recreate the file. I am not that familiar with IsolatedStorageFiles so this is a wild guess.

Upvotes: 4

Related Questions