简体   繁体   中英

How to delete selected node from XML in C#?

I am New To C# I have problem... I want to delete selected node from My XMl File Here I just tried with this code but I didn't get please can any one help in that

private void btnDelete_Click(object sender, EventArgs e)
{
    xdoc.Load(strFilename);
    string Xpath = string.Format("root/{0}/{1}",_strProCat,_strProdType);
    xdoc.SelectSingleNode(Xpath).RemoveAll();

    xdoc.Save(strFilename);
    MessageBox.Show("Deleted Successfully");
}

Here My Xml File

<root>
  <product category="Soaps">
   <product type="Washing">
     <product name="Rin">
      <Id>100</Id>
      <AvailProducts>30</AvailProducts>
      <Cost>20.00</Cost>
   </product>
  <product name="Tide">
    <Id>101</Id>
    <AvailProducts>30</AvailProducts>
    <Cost>15.00</Cost>
  </product>
 </product>
</product>
</root>

Just I want to delete Node which product name="Tide"

You can simple use the below code:

private void btnDelete_Click(object sender, EventArgs e)
{
    var xDoc = XDocument.Load(strFilename);

    foreach (var elem in xDoc.Document.Descendants("product"))
    {
        foreach (var attr in elem.Attributes("name"))
        {
            if (attr.Value.Equals("Tide"))
                elem.RemoveAll();
        }
    }

    xDoc.Save(destinationFilename);
    MessageBox.Show("Deleted Successfully");
}

Happy Coding...

这样的事情应该做到:

xdoc.Elements("product").Where(x=> x.Element("name").Value == "Tide").FirstOrDefault().Remove();

If you want XPath with XmlDocument then following is the way to do it..

XmlDocument xdoc = new XmlDocument();
xdoc.Load(strFilename);
string Xpath = string.Format("root/product[@category='{0}']/product[@type='{1}']/product[@name='{2}']", "Soaps", "Washing", "Tide");
xdoc.SelectSingleNode(Xpath).RemoveAll();
xdoc.Save(strFilename);

Update

As per your Requirement To Remove the empty node , try following code to remove empty node as

XmlNodeList emptyElements = xdoc.SelectNodes(@"//*[not(node())]");
for (int i = emptyElements.Count - 1; i > -1; i--)
{
     XmlNode nodeToBeRemoved = emptyElements[i];
     nodeToBeRemoved.ParentNode.RemoveChild(nodeToBeRemoved);
}

Now your final full flesh code will look like as

string Xpath = string.Format("root/product[@category='{0}']/product[@type='{1}']/product[@name='{2}']", "Soaps", "Washing", "Tide");                      
xdoc.SelectSingleNode(Xpath).RemoveAll();
XmlNodeList emptyElements = xdoc.SelectNodes(@"//*[not(node())]");

for (int i = emptyElements.Count - 1; i > -1; i--)
{
      XmlNode nodeToBeRemoved = emptyElements[i];
      nodeToBeRemoved.ParentNode.RemoveChild(nodeToBeRemoved);
}
xdoc.Save(strFilename);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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