9

Using C#

How do you remove a specific node from an XMLDocument using XPATH?

mrbradleyt
  • 2,312
  • 7
  • 33
  • 38
  • here is the answer http://stackoverflow.com/questions/20611/removing-nodes-from-an-xmldocument – Rakesh Oct 27 '14 at 16:19

3 Answers3

19

If you want to delete nodes, that are not direct children of the documents root, you can do this:

XmlDocument doc = new XmlDocument();
// ... fill or load the XML Document
XmlNode childNode = doc.SelectSingleNode("/rootnode/childnode/etc"); // apply your xpath here
childNode.ParentNode.RemoveChild(childNode);
jocheng
  • 372
  • 4
  • 11
4

Here you go. ChildNodeName, could be just the node name or an XPath query.

XmlDocument doc = new XmlDocument();

// Load you XML Document

XmlNode childNode = doc.SelectSingleNode(childNodeName);

// Remove from the document
doc.RemoveChild(childNode);

There is a different way using Linq, but I guessed you were using .NET 2.0

David Basarab
  • 72,212
  • 42
  • 129
  • 156
2

XPath can only select nodes from a document, not modify the document.

Oliver Hallam
  • 4,242
  • 1
  • 24
  • 30
  • 3
    Technically correct however you can modify an XML document using the System.Xml library. XPath will help you get to the correct part of the xml document in order to manipulate it. – Vidar Oct 18 '11 at 15:04