I have an XML document, where I need to add and remove some nodes while iterating through. But if I'll add nodes like that, the other nodes will be shifted depending on InsertAfter
or RemoveChild
. So xNode.ChildNodes[i]
will point to the wrong node. Of course, I can add or substract counter, but I think it's not a best way. How should I do this?
void Init()
{
XmlDocument doc = LoadDocument("test.xml");
RecursiveProcess(doc);
}
void RecursiveProcess(XmlNode xNode)
{
for(int i = 0; i < node.ChildNodes.Count; i++)
{
XmlElement node = xNode.ChildNodes[i] as XmlElement;
if(/*some condition*/)
{
var x = Document.CreateElement("newNode");
node.ParentNode.InsertAfter(x, node);
}
else if(...)
{
var x = Document.CreateElement("anotherNode");
node.ParentNode.RemoveChild(node);
}
RecursiveProcess(node);
}
}