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

C# XDocument保存后XML文件中的额外字符,c#,xml,windows-phone-8,linq-to-xml,C#,Xml,Windows Phone 8,Linq To Xml,我正在使用XDocument用独立存储更新XML文件。但是,保存更新后的XML文件后,会自动添加一些额外字符 以下是更新前的XML文件: <inventories> <inventory> <id>I001</id> <brand>Apple</brand> <product>iPhone 5S</product> <price>750</pric

我正在使用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>

当我在Python中遇到类似的问题时,我发现我正在覆盖文件的开头,而没有在之后截断它

看看你的代码,我想你可能也这么做了:

stream.Position=0;
单据保存(流);
stream.Close();
尝试将流长度设置为其后期保存位置,如下所示:

stream.Position=0;
单据保存(流);
流设置长度(流位置);
stream.Close();

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

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);
}

听起来你好像是从多个线程写入同一个文件-你应该检查你的代码,添加日志,断点,等等。我已经编辑了你的标题。请看,“,其中的共识是“不,他们不应该”。许多年后。。。但这为我解决了问题。在F#中:使用fs=newfilestream(filepath,FileMode.OpenOrCreate);xDocument.Save(fs);fs.设置长度(fs.位置);fs.Close();
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));
        }
    }
}
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);
}