在对它们进行更改后,我无法保存 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 的同时正确编写此文件?