繁体   English   中英

从从列表框C#中选择的xml文件中删除节点

[英]Delete a node from xml file selected from a listbox C#

我正在尝试删除xml文件中的节点,其名称由列表框指定(列表框中仅显示每个设置的,我需要删除该名称下的每个设置),但我尝试了所有操作无法使其工作。 这是我尝试的列表:

private void dlt_btn_Click(object sender, EventArgs e)
    {

        string selectednode = Convert.ToString(listBox1.SelectedItem);

        XmlDocument doc = new XmlDocument();
        doc.Load("dati.txt");

        XmlNodeList nodes = doc.GetElementsByTagName(selectednode);
        XmlNode node = nodes[0];
        node.ParentNode.RemoveChild(node);

        doc.Save("dati.txt");
    }

这是xml文件:

<?xml version="1.0"?>
<DATA>
  <name>wewe4</name>
  <SETTING_LIST>
    <setting>
      <name>Ping</name>
      <enable>config</enable>
      <disable>config</disable>
      <check>config</check>
      <word>ping</word>
      <ifchecktrue>true</ifchecktrue>
      <usegrep>true</usegrep>
    </setting>
    <setting>
      <name>Pong</name>
      <enable>config</enable>
      <disable>config</disable>
      <check>config</check>
      <word>ping</word>
      <ifchecktrue>true</ifchecktrue>
      <usegrep>true</usegrep>
    </setting>
    </DATA>

如果我了解您,这就是使用System.Xml.Linq.XDocument此代码不使用XmlDocument XDocument是较新的API:

XDocument doc = XDocument.Load("dati.txt");

doc.Descendants().Elements("name")           //all "name" elements
    .Where(d => d.Value == selectednode)     //where node value is user input
    .Where(d => d.Parent.Name == "setting")  //and also its parent element name is "setting"
    .Select(d => d.Parent)                   //Select name's parent
    .Remove();                               //Remove it

//optionally save the xml back to the file or whatever you intend to do with it.

暂无
暂无

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

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