Search code examples
c#xmllinq-to-xml

Extra characters in XML file after XDocument Save


I'm using XDocument to update an XML file with Isolated Storage. However, after saving the updated XML file, some extra characters are added automatically.

Here is my XML file before update:

<inventories>
  <inventory>
    <id>I001</id>
    <brand>Apple</brand>
    <product>iPhone 5S</product>
    <price>750</price>
    <description>The newest iPhone</description>
    <barcode>1234567</barcode>
    <quantity>75</quantity>
  <inventory>
</inventories>

Then after the file is updated and saved, it becomes this, with a trailing ies>:

<inventories>
  <inventory>
    <id>I001</id>
    <brand>Apple</brand>
    <product>iPhone 5S</product>
    <price>750</price>
    <description>The best iPhone</description>
    <barcode>1234567</barcode>
    <quantity>7</quantity>
  <inventory>
</inventories>ies>

I've spent a lot of time trying to find and fix the problem but no solutions were found. The solution in xdocument save adding extra characters cannot help me fix my problem.

Here's my C# code:

private void UpdateInventory(string id)
{
    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream stream = isf.OpenFile("inventories.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            XDocument doc = XDocument.Load(stream);
            var item = from c in doc.Descendants("inventory")
                        where c.Element("id").Value == id
                        select c;
            foreach (XElement e in item)
            {
                e.Element("price").SetValue(txtPrice.Text);
                e.Element("description").SetValue(txtDescription.Text);
                e.Element("quantity").SetValue(txtQuantity.Text);
            }
            stream.Position = 0;
            doc.Save(stream);
            stream.Close();
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }
    }
}

Solution

  • The most reliable way is to re-create it:

    XDocument doc; // declare outside of the using scope
    using (IsolatedStorageFileStream stream = isf.OpenFile("inventories.xml", 
               FileMode.Open, FileAccess.Read))
    {
        doc = XDocument.Load(stream);
    }
    
    // change the document here
    
    using (IsolatedStorageFileStream stream = isf.OpenFile("inventories.xml", 
           FileMode.Create,    // the most critical mode-flag
           FileAccess.Write))
    {
       doc.Save(stream);
    }