I'm using XDocument to update the XML file with Isolated Storage. However, after save 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:
<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 the post 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));
}
}
}
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);
}
When I had a similar problem in Python, I discovered that I was overwriting the beginning of the file without truncating it afterwards.
Looking at your code, I'd say you might be doing the same:
stream.Position = 0;
doc.Save(stream);
stream.Close();
Try setting the stream length to its post-save location as per this answer:
stream.Position = 0;
doc.Save(stream);
stream.SetLength(stream.Position);
stream.Close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With