简体   繁体   English

如何从XML文件删除条目?

[英]How do I delete an entry from an XML file?

I have the xml information populate in a listBox(lstAnimals). 我将XML信息填充在listBox(lstAnimals)中。 I can delete from the listBox with the following code: 我可以使用以下代码从listBox中删除:

 private void btnAdopt_Click(object sender, EventArgs e)
    {
        DialogResult result = MessageBox.Show("Complete Adoption?", "Found a Happy Home!", MessageBoxButtons.YesNo);
        if (result == DialogResult.Yes)
        {

            if (lstAnimals.SelectedIndex >= 0)
                lstAnimals.Items.Remove(lstAnimals.SelectedItem);                                                        

        }
        else
        {
            return;
        }

However, when the list is updated/program opened, that entry repopulates into the listBox. 但是,当更新列表/打开程序时,该条目将重新填充到listBox中。 How can I delete this from the XML document simultaneously with the lixtBox? 如何与lixtBox同时从XML文档中删除它?

Here is the xml: 这是xml:

<?xml version="1.0" encoding="UTF-8"?>
 <Animals>
  <Animal>
   <Name>Bruce</Name>
   <Type>Dog</Type>
   <Age>Adult</Age>
  </Animal>
  <Animal>
   <Name>Gizmo</Name>
   <Type>Cat</Type>
   <Age>Senior</Age>
  </Animal>
 </Animals>

I was asked how I populate my listBox, so here is the code: 我被问到如何填充列表框,所以代码如下:

private void UpdateList() 
    {         
        var an = XElement.Load(@"Animals.xml")
            .Descendants("Animal")
            .OrderBy(xe => (xe.Element("Name").Value))
            .ToList<XElement>();

        lstAnimals.Items.Clear();

        foreach (var a in an)
            lstAnimals.Items.Add(new Animal()
            {
                name = a.Element("Name").Value.ToString(),
                type = a.Element("Type").Value,
                age = a.Element("Age").Value
            });
    }

Picture of what the listBox presents as: http://img.photobucket.com/albums/v84/Shades9323/shelterapp_zps4c22868c.jpg listBox呈现的图片为: http : //img.photobucket.com/albums/v84/Shades9323/shelterapp_zps4c22868c.jpg

You can use XmlDocument removeChild method similar to this 您可以使用类似于此的XmlDocument removeChild方法

XmlDocument doc ;

doc = new XmlDocument(); 
doc.Load("path to your XML file");

XmlNode animalNode;
XmlNode root = doc.DocumentElement;

animalNode=root.SelectSingleNode("descendant::Animal[Name='" + lstAnimals.SelectedItem + "']");
doc.RemoveChild(animalNode) ;

//save the XML file

Add this code into your button click event 将此代码添加到您的按钮单击事件中

        string text = lstAnimals.SelectedItem.ToString();
        string animalName = text.Substring(0, text.IndexOf("is")).Trim();           
        XDocument xDoc = XDocument.Load("Animals.xml"); //here is your filepath
        XElement element = (from x in xDoc.Descendants("Animal")
            where x.Element("Name").Value == animalName  
            select x).First();
        element.Remove();
        xDoc.Save("Animals.xml");
        lstAnimals.Items.Remove(lstAnimals.SelectedItem);

Ofcourse if you add Id property to your animals,it will be easier.Just store id variable into your listBox Items "Tag" property.. 当然,如果将Id属性添加到动物中,则将更加容易。只需将id变量存储到listBox Items的“ Tag”属性中即可。

Here how you can do it using linq to xml 在这里,您如何使用linq to xml做到这一点

     private void btnAdopt_Click(object sender, EventArgs e)
    {
        DialogResult result = MessageBox.Show("Complete Adoption?", "Found a Happy Home!", MessageBoxButtons.YesNo);
        if (result == DialogResult.Yes)
        {

            if (lstAnimals.SelectedIndex >= 0)
{
                lstAnimals.Items.Remove(lstAnimals.SelectedItem);  
XDocument xDoc = XDocument.Load("test.xml");
            xDoc.Descendants("Animal").Where(x => x.Element("Name").Value.ToString() == lstAnimals.SelectedItem ).Remove();
            xDoc.Save("test1.xml"); 

}                                                      

        }
        else
        {
            return;
        }

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

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