convert dom4j docment to W3c document

感情迁移 提交于 2021-02-07 07:45:17

问题


i'm need to convert an xml build with dom4j to w3c document and don't have any idea about how do it...


回答1:


I'm assuming you want to go from:

org.dom4j.Document

To:

org.w3c.dom.Document

From the dom4j quick start guide:

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

From a JavaRanch example on String to 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 the 2 and you should have what you need.




回答2:


Check out 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)



回答3:


If you have large documents, you may want to avoid serializing your Document to text for performance reasons. In that case, it's best to use SAX events directly to do the transformation:

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


来源:https://stackoverflow.com/questions/4181116/convert-dom4j-docment-to-w3c-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!