gpt4 book ai didi

java - 如何用新节点替换dom节点?

转载 作者:行者123 更新时间:2023-11-30 06:31:00 25 4
gpt4 key购买 nike

我想用我创建的新节点替换现有的 Dom 节点。我将其实现为

String messageBody=" <imgGroup><img src="src" width="width" height="height" alt="alt" type="type" orient="orient"/></imgGroup>"
File file=new File("doc.xml");
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
doc = docBuilder.parse(file);
Element node = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream(messageBody.getBytes()))
.getDocumentElement();
System.out.println(node.getClass());
doc.getDocumentElement().replaceChild((Node)node, doc.getDocumentElement().getFirstChild());
}catch(Exception e){
e.printStackTrace();
}

我遇到运行时错误WRONG_DOCUMENT_ERR:节点在与创建它的文档不同的文档中使用。

谁能建议如何以不同的方式做到这一点?

最佳答案

需要采用新文档的节点,调用Document.adoptNode() .请注意,adoptNode() 本身不会将节点添加到目标文档中的任何位置,只允许您将其添加到 DOM 树中。之后您仍然需要调用 replaceChild()

关于java - 如何用新节点替换dom节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9990863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com