问题
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