我無法在對它們進行更改後保存xml文件。我今天花了整整一天的時間試圖弄清楚這一點,而且我無處可去。XML,LINQ和XDocument.Save問題
我有這樣的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.ReadWriteNoCopyOnWrit e爲OpenAsync文件結束爲0字節。
任何人都知道如何在仍使用XDocument.Save的情況下正確編寫此文件?
您是否在Save()調用之後關閉或處置流? – Steve
掛上,不完整,需要測試。 –
我遺漏了Dispose,但它的行爲與此相同。 – AveryPierce