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

问题描述 投票:6回答:2

我正在使用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));
        }
    }
}
c# xml windows-phone-8 linq-to-xml
2个回答
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);
}

1
投票

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

看看你的代码,我会说你可能会这样做:

stream.Position = 0;
doc.Save(stream);
stream.Close();

尝试按照this answer将流长度设置为其保存后的位置:

stream.Position = 0;
doc.Save(stream);
stream.SetLength(stream.Position);
stream.Close();
© www.soinside.com 2019 - 2024. All rights reserved.