1
我正在用下面的代碼從xml中刪除元素;從xml中刪除元素後,XDocument在末尾添加一行
StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile MyFile = await localFolder.GetFileAsync("CustomTV.xml");
var stream4 = await MyFile.OpenStreamForReadAsync();
XDocument myXml2 = XDocument.Load(stream4);
myXml2.Element("channelLists")
.Elements("channellist")
.Where(x => (string)x.Attribute("lname") == lnameselectedText)
.Remove();
using (var stream = await (await ApplicationData.Current.LocalFolder.CreateFileAsync("CustomTV.xml", CreationCollisionOption.OpenIfExists)).OpenAsync(FileAccessMode.ReadWrite))
{
myXml2.Save(stream.AsStreamForWrite());
}
在刪除具有屬性「lname = name3」的元素之前;
<?xml version="1.0" encoding="utf-8"?>
<channelLists>
<channellist lname="name1" />
<channellist lname="name2" />
<channellist lname="name3" />
<channellist lname="name4" />
</channelLists>
刪除後;
<?xml version="1.0" encoding="utf-8"?>
<channelLists>
<channellist lname="name1" />
<channellist lname="name2" />
<channellist lname="name4" />
</channelLists>lname="name4"/> //It adds all the time this line with last elements attribute.
</channelLists>
什麼問題?
我認爲這是原因,但這一次我得到「訪問被拒絕」調試警報。 – user2542030
在寫入修改的xml之前關閉用於加載現有xml的流? – har07
編輯:我添加了「stream4.Dispose();」 line「after XDocument myXml2 = XDocument.Load(stream4);」並做了@ har07說,問題解決了。 – user2542030