【发布时间】:2017-06-22 22:44:00
【问题描述】:
我在对 xml 文件进行更改后无法保存它们。我今天花了一整天的时间试图弄清楚这一点,但我一无所获。
我有这个 xml 文档:
<?xml version=1.0" encoding="utf-8"?>
<content>
<weapon id="1234" name="blahblah">
<note info="blah blah" />
</weapon>
<weapon id="5678" name="blahblah2">
<note info="blah blah" />
</weapon>
</content>
这是我迄今为止想出的,但并不完全有效(编辑以显示我如何读取文件):
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".xml");
StorageFile gfile = await openPicker.PickSingleFileAsync()
fileContent = await FileIO.ReadTextAsync(gfile, Windows.Storage.Streams.UnicodeEncoding.Utf8);
Xdocument xml = XDocument.Parse(fileContent);
xml.Descendants("weapon").Where(c => c.Attribute("id").Value.Equals("5678")).FirstorDefault().Remove();
IRandomAccessStream writeStream = await gfile.OpenAsync(FileAccessMode.ReadWrite);
Stream stream = writeStream.AsStreamForWrite();
xml.Save(stream);
生成的 xml 文档将是这样的:
<?xml version=1.0" encoding="utf-8"?>
<content>
<weapon id="1234" name="blahblah">
<note info="blah blah" />
</content>apon>
<weapon id="5678" name="blahblah2">
<note info="blah blah" />
</weapon>
</content>
如果我尝试将 FileAccessMode.ReadWriteNoCopyOnWrite 用于 OpenAsync,则文件最终为 0 字节。
有人知道我如何在仍然使用 XDocument.Save 的同时正确编写此文件吗?
【问题讨论】:
-
在调用 Save() 后,您是关闭还是释放流?
-
等一下,不完整,需要测试。
-
我省略了 Dispose 但它的作用相同。
标签: c# xml windows-8 windows-runtime