将dom4j文档转换为W3c文档

时间:2010-11-15 03:09:06

标签: java xml w3c dom4j

我需要将带有dom4j的xml构建转换为w3c文档,并且不知道它是如何做到的......

3 个答案:

答案 0 :(得分:8)

查看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)

答案 1 :(得分: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();
}

答案 2 :(得分: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,你应该得到你需要的东西。