我需要将使用 dom4j 构建的 XML 转换为 w3c 文档,但不知道如何操作。
查看 DOMWriter。这对我有用:
import org.dom4j.DocumentHelper;
import org.dom4j.io.DOMWriter;
org.dom4j.Document dom4jDoc = DocumentHelper.createDocument();
org.w3c.dom.Document w3cDoc = new DOMWriter().write(dom4jDoc)
我假设您想从:
org.dom4j.Document
致:
org.w3c.dom.Document
来自 dom4j 快速入门指南:
Document document = ...;
String text = document.asXML();
来自 JavaRanch 示例,关于字符串到文档:
public static Document stringToDom(String xmlSource)
throws SAXException, ParserConfigurationException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(new StringReader(xmlSource)));
}
将 2 者结合起来,你应该得到你所需要的。
如果您有大型文档,出于性能原因,您可能希望避免将文档序列化为文本。在这种情况下,最好直接使用 SAX 事件来进行转换:
private static final TransformerFactory transformerFactory =
TransformerFactory.newInstance();
public static org.w3c.dom.Document toW3c(org.dom4j.Document dom4jdoc)
throws TransformerException {
SAXSource source = new DocumentSource(dom4jdoc);
DOMResult result = new DOMResult();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(source, result);
return (org.w3c.dom.Document) result.getNode();
}