2016-05-10 131 views
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> 

什麼問題?

回答

0

看起來像您的代碼在原始XML上寫入修改後的XML。這就是爲什麼你看到它定位成超過延長修改的XML的原始XML的提醒:

lname="name4"/> 
</channelLists> 

這就是說,CreationCollisionOption.ReplaceExisting可能是在這種情況下更合適。

+0

我認爲這是原因,但這一次我得到「訪問被拒絕」調試警報。 – user2542030

+0

在寫入修改的xml之前關閉用於加載現有xml的流? – har07

+1

編輯:我添加了「stream4.Dispose();」 line「after XDocument myXml2 = XDocument.Load(stream4);」並做了@ har07說,問題解決了。 – user2542030

相關問題