Convert dom4j document to W3c document

I need to convert the xml assembly from dom4j to a w3c document and have no idea how to do this ...

+4
source share
3 answers

I assume you want to go from:

org.dom4j.Document 

To:

 org.w3c.dom.Document 

In a quick start guide with dom4j :

 Document document = ...; String text = document.asXML(); 

From the JavaRanch example in String for the document:

 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))); } 

Combine 2, and you should get what you need.

+4
source

If you have large documents, you can avoid serializing the document in the text for performance reasons. In this case, it is best to use SAX events to convert:

 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(); } 
+6
source

Check out the DOMWriter. This works for me:

 import org.dom4j.DocumentHelper; import org.dom4j.io.DOMWriter; org.dom4j.Document dom4jDoc = DocumentHelper.createDocument(); org.w3c.dom.Document w3cDoc = new DOMWriter().write(dom4jDoc) 
+6
source

All Articles