XDocument保存后XML文件中的额外字符

Trü*_* Ds 6 c# xml linq-to-xml windows-phone-8

我正在使用XDocument来使用独立存储更新XML文件.但是,保存更新的XML文件后,会自动添加一些额外的字符.

这是我更新前的XML文件:

<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>
Run Code Online (Sandbox Code Playgroud)

然后在更新并保存文件后,它变为:

<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>
Run Code Online (Sandbox Code Playgroud)

我花了很多时间试图找到并解决问题,但没有找到解决方案.邮件xdocument中的解决方案保存添加额外的字符无法帮助我解决我的问题.

这是我的C#代码:

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 2

最可靠的方法是重新创建它:

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);
}
Run Code Online (Sandbox Code Playgroud)