我正在使用以下代码从xml中删除元素;
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 :(得分:0)
看起来您的代码在原始XML之上编写了修改后的XML。这就是为什么你看到原始XML的提醒,它位于修改后的XML的扩展之外:
lname="name4"/>
</channelLists>
尽管如此,CreationCollisionOption.ReplaceExisting
在这种情况下可能更合适。