I am trying to remove some nodes from XML document based on input but getting below error...
The node to be removed is not a child of this node.
XmlDocument document = new XmlDocument();
document.Load(filePath);
if (document == null)
throw new Exception("Unable to load document.");
foreach (string xPath in xPaths)
{
XmlNodeList oldChild = document.SelectNodes(xPath, mgr);
if (oldChild != null)
{
foreach (XmlNode child in oldChild)
{
document.RemoveChild(child);
}
}
}
document.Save(filePath);
Can anyone help me with what I am missign here.
The RemoveChild method working on direct child of the node. you are trying to remove some inner (not first generation) node by accessing the root node - the document. The trick here is to get the parent node and remove the child from it.
child.ParentNode.RemoveChild(child)