Delete node in XML file

My XML file:

<?xml version="1.0" encoding="utf-8"?>
 <WebServices>
  <WebService>
   <Name>ServiceA</Name>
   <Uri>http://localhost:53683/api/home</Uri>
  </WebService>

  <WebService>
   <Name>ServiceB</Name>
   <Uri>http://localhost:50043/api/home</Uri>
  </WebService>
 </WebServices>

I want to delete node by Name. My code doesn't work.

 XDocument document = XDocument.Load(this.Path);
 //xDoc.Element("WebServices").Element("WebService").Elements("Name").Where(node => node.Value == "Name1").Remove();
   document.Save(this.Path);

It removes only "Name" node in WebService. I want to remove the "WebService" node from "WebServices". Any one can help?

Jon Skeet
people
quotationmark

Well, you've selected the child element - so you just need to select its parent:

xDoc.Root
    .Elements("WebService")
    .Elements("Name")
    .Where(node => node.Value == "Name1")
    .Select(node => node.Parent)
    .Remove();

Or you could change your Where call:

xDoc.Root
    .Elements("WebService")
    .Where(ws => (string) ws.Element("Name") == "Name1")
    .Remove();

people

See more on this question at Stackoverflow