简体   繁体   English

遍历 XML 节点,添加和删除一些

[英]Iterate through XML nodes, add and remove some

I have an XML document, where I need to add and remove some nodes while iterating through.我有一个 XML 文档,我需要在迭代时添加和删除一些节点。 But if I'll add nodes like that, the other nodes will be shifted depending on InsertAfter or RemoveChild .但是,如果我添加这样的节点,其他节点将根据InsertAfterRemoveChild So xNode.ChildNodes[i] will point to the wrong node.所以xNode.ChildNodes[i]将指向错误的节点。 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在主文档处理之后,我遍历队列并执行添加/删除操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM