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);
}
}
I've found a solution. I have created two queues
NodesToRemove = new Queue<OpenXmlElement>();
NodesToInsert = new Queue<Tuple<OpenXmlElement, OpenXmlElement, InsertMode>>();
And after main document processing I iterate throug the queues and do add/remove operations
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.