C#从XML列表中删除项目

时间:2018-03-16 14:41:16

标签: c# xml list uwp

我写了一些UWP应用程序。我想在XML列表中保存/更新/删除。我的XML列表看起来像:

<?xml version="1.0" encoding="utf-8"?>
<rootnode>
    <Kunde Name="Testkunde" />
    <Kunde Name="Testkunde2" />
</rootnode>

如果我想删除包含此代码的项目

StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(@"C:\Users\IT\source\repos\App3\App3");
StorageFile file = await folder.GetFileAsync("Kundenliste.xml");

using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    Stream s = writeStream.AsStreamForWrite();
    XDocument doc = XDocument.Load(s);

    var q = from node in doc.Descendants("Kunde")
        let attr = node.Attribute("Name")
        where attr != null && attr.Value == "Testkunde"
        select node;

    q.ToList().ForEach(x => x.Remove());
    doc.Save(s);
}

发生这种情况

<?xml version="1.0" encoding="utf-8"?>
<rootnode>
    <Kunde Name="Testkunde" />
  <Kunde Name="Testkunde2"  />
</rootnode><?xml version="1.0" encoding="utf-8"?>
<rootnode>
  <Kunde Name="Testkunde2" />
</rootnode>

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

只需设置

s.Position = 0;
s.SetLength(0);

Stream s = writeStream.AsStreamForWrite();
XDocument doc = XDocument.Load(s);

它会起作用