2010-11-15 52 views

回答

4

我假设你想从去任何想法:

org.dom4j.Document 

要:

org.w3c.dom.Document 

dom4j quick start guide

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

从上串一个JavaRanch example到文档中:

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,你应该有你需要的东西。

6

如果您有大型文档,您可能希望避免将文档序列化为文本以达到性能原因。在这种情况下,最好直接使用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(); 
} 
+0

非常感谢,这工作很好! – 2011-10-04 22:13:18

6

检出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) 
+0

完美的作品,谢谢 – Anand 2014-03-18 08:53:24