Replacing XML node via Java

后端 未结 2 829
情书的邮戳
情书的邮戳 2021-01-18 17:08

I wan to replace a node in XML document with another and as a consequence replace all it\'s children with other content. Following code should work, but for an unknown reaso

2条回答
  •  清歌不尽
    2021-01-18 17:46

    Try using replaceChild to do the whole hierarchy at once:

    NodeList nodes = doc.getElementsByTagName("NodeToReplace");
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Node newNode = // Create your new node here.
        node.getParentNode().replaceChild(newNode, node);
    }
    

提交回复
热议问题