简体   繁体   English

如何在C#中从XML删除元素

[英]How do I remove an Element from an XML in C#

I have the following XML File: 我有以下XML文件:

<HOUSE>
  <LOCATION>Random</LOCATION>
  <SERVER>A</SERVER>
  <SERVER>B</SERVER>
  <SERVER>C</SERVER>
  <SERVER>D</SERVER>
  <SERVER>E</SERVER>
  <SERVER>F</SERVER>
</HOUSE>

I'm using a ListBox that stores the SERVER items and I want add a function that removes a selected item from the listbox and the XML file. 我正在使用一个存储SERVER项的ListBox ,并且我想添加一个从列表框和XML文件中删除选定项的函数。 I've tried using: 我试过使用:

doc.Element("HOUSE")
   .Element("SERVER")
   .Element(Serverslstbox.SelectedItem.ToString())
   .Remove();

and

XmlElement root = doc.DocumentElement;
        XmlNode remove= root.SelectSingleNode(Serverslstbox.SelectedItem.ToString());
        doc.ParentNode.RemoveChild(remove);

and many other options but none of them seem to work, any suggestions? 和许多其他选项,但似乎都不起作用,有什么建议吗?

Assuming that Serverslstbox.SelectedItem contains the name of the server like "A", "B"... 假设Serverslstbox.SelectedItem包含服务器名称,例如“ A”,“ B” ...

Then you need to use Where to filter the elements by their value like this: 然后,您需要使用Where来按其值过滤元素,如下所示:

doc.Element("HOUSE")
    .Elements("SERVER")
    .Where(x => x.Value == Serverslstbox.SelectedItem.ToString())
    .Remove();

The above query will remove all "SERVER" elements inside the "HOUSE" element where the value equals the selected item value. 上面的查询将删除值等于所选项目值的“ HOUSE”元素内的所有“ SERVER”元素。

To save the result to a file use the Save method like this: 要将结果保存到文件中,请使用Save方法,如下所示:

doc.Save(filename);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM