Search code examples
c#.netxmlxpathxmldocument

Deleting XML using a selected Xpath and a for loop


I currently have the following code:

XPathNodeIterator theNodes = theNav.Select(theXPath.ToString());

while (theNodes.MoveNext())
{
    //some attempts i though were close
    //theNodes.RemoveChild(theNodes.Current.OuterXml);
    //theNodes.Current.DeleteSelf();
}

I have set xpath to what I want to return in xml and I want to delete everything that is looped. I have tried a few ways of deleting the information but it does't like my syntax. I found an example on Microsoft support: http://support.microsoft.com/kb/317666 but I would like to use this while instead of a for each.

Any comments or questions are appreciated.


Solution

  • string nodeXPath = "your x path";
    
    XmlDocument document = new XmlDocument();
    document.Load(/*your file path*/);
    
    XmlNode node = document.SelectSingleNode(nodeXPath);
    node.RemoveAll();
    
    XmlNode parentnode = node.ParentNode;
    parentnode.RemoveChild(node);
    document.Save("File Path");