I’m trying to modify an XmlDocument by deleting nodes from it while I’m iterating through the candidate set of nodes. The problem I’m having is that even though nodes has 206 elements, MoveNext() is returning false after element 1.
Could this be because I’m modifying the data? How can I get around this? Or is there anothe reason I’m missing? My code is below.
Any other way of accomplishing the same thing (selectively deleting nodes from an XML file) would work fine too.
XmlReader reader = XmlReader.Create(myFile.FullName);
// Load document
XmlDocument document = new XmlDocument();
document.Load(reader);
XPathNavigator navigator = document.CreateNavigator();
// Select elementD nodes with the correct format (there are other elementD nodes that we
// want to ignore
XPathNodeIterator nodes = navigator.Select("/elementA/elementB/elementC/elementB/elementD");
// Keep count of how many nodes we've deleted
int count = 0;
while (nodes.MoveNext)
{
moreNodes = nodes.MoveNext();
XPathNavigator node = nodes.Current;
logger.log(node.ToString());
string name = node.GetAttribute("name", "");
// If name isn't a valid name, delete it from the document
if (!validNames.Contains(name))
{
count++;
// Get the parent node (elementB)
XPathNavigator elementBNode = node.SelectSingleNode("..");
// And its parent node (elementC)
XPathNavigator elementCNode = elementBNode.SelectSingleNode("..");
// Delete the elementB node
elementBNode.DeleteSelf();
// It the elementC node is empty, then delete it as well
if (!elementCNode.HasChildren)
{
elementCNode.DeleteSelf();
}
}
}
// Make sure the document gets formatted nicely
XmlWriterSettings settings= new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" ");
// Write out the modified document
XmlWriter writer = XmlWriter.Create(myFile + ".modified", settings);
document.WriteTo(writer);
From the documentation here (under “Remarks”):