XDocument保存后XML文件中有多余字符

7

我将使用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>

然后,文件被更新并保存后,它变成:
<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>

我花了很多时间尝试寻找和解决问题,但是没有找到解决方案。这篇帖子中的解决方案 xdocument save adding extra characters 不能帮助我解决我的问题。

这是我的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));
        }
    }
}

2
听起来你好像在多个线程中写入同一个文件 - 你应该检查你的代码,添加日志记录、断点等。 - cacau
1
我已经编辑了你的标题。请参考“问题的标题应该包含“标签”吗?”,在那里达成共识是“不应该”。 - John Saunders
2个回答

2
当我在Python中遇到类似的问题时,我发现我在没有截断文件的情况下覆盖了文件的开头。
看着你的代码,我想说你可能也是同样的问题。
stream.Position = 0;
doc.Save(stream);
stream.Close();

尝试按照这个答案的建议,将流长度设置为保存后的位置:
stream.Position = 0;
doc.Save(stream);
stream.SetLength(stream.Position);
stream.Close();

多年以后...但这对我解决了问题。在F#中:use fs = new FileStream(filepath, FileMode.OpenOrCreate); xDocument.Save(fs); fs.SetLength(fs.Position); fs.Close(); - drkmtr

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接