2014-03-25 95 views
5

我正在使用XDocument来更新具有独立存储的XML文件。但是,保存更新后的XML文件后,会自动添加一些额外的字符。XDocument保存后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

我编辑了你的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –

回答

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