1

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?

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

You can use xPath

XElement element = document.XPathSelectElement("//WebService[Name = 'ServiceA']");
element.Romove();

Comments

0

You can try linq to xml

XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")

let attr = node.Attribute("name")
where attr != null && attr.Value == "File1"

select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");

or this below one

XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");

for (int i = nodes.Count - 1; i >= 0; i--)
{
 nodes[i].ParentNode.RemoveChild(nodes[i]);
}
doc.Save(path);

If you need a class in order to delete you can also try below

private static void DeleteXmlNode(string path, string tagname, string searchconditionAttributename, string searchconditionAttributevalue)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(path); 
    XmlNodeList nodes = doc.GetElementsByTagName(tagname);\
   //XmlNodeList nodes = doc.GetElementsByTagName("user");
    foreach (XmlNode node in nodes)
    {
        foreach (XmlAttribute attribute in node.Attributes)
        {
            if ((attribute.Name == searchconditionAttributename) && (attribute.Value == searchconditionAttributevalue))
            //if ((attribute.Name == "name") && (attribute.Value == "aaa"))
            {
                //delete.
                node.RemoveAll();
                break;
            }
        }
    }
    //save xml file.
    doc.Save(path);
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.