我在更改 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>
如果我尝试对 OpenAsync 使用 FileAccessMode.ReadWriteNoCopyOnWrite,文件最终为 0 字节。
任何人都知道如何在仍然使用 XDocument.Save 的同时正确编写此文件?
最佳答案
为什么不直接使用 System.IO.File.WriteAllText?
XDocument xml = XDocument.Load(xmlFilePath);
System.IO.File.WriteAllText(xmlFilePath, string.Format(@"<?xml version=""1.0""?>{0}{1}", Environment.NewLine, xml));
关于c# - XML、LINQ 和 XDocument.Save 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10746776/