有一个similar post using w3c dom在 .我想知道如何使用 dom4j 做到这一点。我想插入<div id="dynamicdiv"/>
作为 body 的第一个元素。 <html><head/><body>[<div id="dynamicdiv">] <many tags></body></html>
最佳答案
谢谢Mat Banik我设法让您的替代方法发挥作用,我将其发布以供其他人受益。您可以同时获得 dom4j 和 w3c dom 的优点。此外,内部只构建了一棵树,这使得 print(document.asXML()) 能够合并 w3c 完成的操作。
列表
package playground;
import java.io.StringReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMDocumentFactory;
import org.dom4j.io.SAXReader;
public class Dom4jInsertBefore {
public static void main(String[] args) throws DocumentException {
String newNode = "<node>value</node>"; // Convert this to XML
String text = "<root><given></given></root>";
// Document document = DocumentHelper.parseText(text); //type casting
// exception will come while converting to DOMDocument
// use DOMDocumentFactory
// Document newNodeDocument = DocumentHelper.parseText(newNode);
DOMDocumentFactory factory = new DOMDocumentFactory();
SAXReader reader2 = new SAXReader();
reader2.setDocumentFactory(factory);
org.dom4j.Document document = reader2.read(new StringReader(text));
Document newNodeDocument = reader2.read(new StringReader(newNode));
Element givenNode = document.getRootElement().element("given");
givenNode.add(newNodeDocument.getRootElement());
org.dom4j.dom.DOMDocument w3cDoc = (DOMDocument) document;
org.w3c.dom.Element e = w3cDoc.createElement("div");
e.setAttribute("id", "someattr");
w3cDoc.getDocumentElement().getFirstChild().insertBefore(e,
w3cDoc.getDocumentElement().getElementsByTagName("node").item(0));
// w3cDoc.getDocumentElement().getFirstChild().appendChild(e); this works
System.out.println(document.asXML());
}
}
输出
<?xml version="1.0" encoding="UTF-8"?>
<root><given><div id="someattr"/><node>value</node></given></root>`
关于java - 如何使用dom4j在java中的另一个xml文档中插入一个xml节点作为第一个子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4665143/