c# - XML、LINQ 和 XDocument.Save 问题

标签 c# xml windows-8 windows-runtime

我在更改 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/

相关文章:

c# - 对象中的特殊字符使 JSON 无效(DataContractJsonSerializer)

c# - 如何在 Controller 操作中访问 $orderBy 等查询参数?

java - 使用 XML 而不是通过注释配置 hibernate 有充分的理由吗?

visual-c++ - 如何检索 Windows 8 中 TSF 管理器使用的文档中的总字符数?

c# - 使用 PostAsync、HttpClient 和 Json 从 C# Metro UI 客户端调用 MVC4 WebAPI 方法

c# - TFS 2018 构建失败,错误 MSB6006 : "csc.exe" exited with code 1

c# - 释放未插入的虚拟串行端口

python - 在 Python 中从文本/PDF 生成 XML 的最佳 Python 库是什么?

java - API 22 与 API 23 中的 Seekbar Progress Drawable 调整大小不同

.net - Visual Basic 的 .Net 4.5 有哪些新功能?