How to I output org.w3c.dom.Element to string format in java? How to I output org.w3c.dom.Element to string format in java? xml xml

How to I output org.w3c.dom.Element to string format in java?


Assuming you want to stick with the standard API...

You could use a DOMImplementationLS:

Document document = node.getOwnerDocument();DOMImplementationLS domImplLS = (DOMImplementationLS) document    .getImplementation();LSSerializer serializer = domImplLS.createLSSerializer();String str = serializer.writeToString(node);

If the <?xml version="1.0" encoding="UTF-16"?> declaration bothers you, you could use a transformer instead:

TransformerFactory transFactory = TransformerFactory.newInstance();Transformer transformer = transFactory.newTransformer();StringWriter buffer = new StringWriter();transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");transformer.transform(new DOMSource(node),      new StreamResult(buffer));String str = buffer.toString();


Simple 4 lines code to get String without xml-declaration (<?xml version="1.0" encoding="UTF-16"?>) from org.w3c.dom.Element

DOMImplementationLS lsImpl = (DOMImplementationLS)node.getOwnerDocument().getImplementation().getFeature("LS", "3.0");LSSerializer serializer = lsImpl.createLSSerializer();serializer.getDomConfig().setParameter("xml-declaration", false); //by default its true, so set it to false to get String without xml-declarationString str = serializer.writeToString(node);


Not supported in the standard JAXP API, I used the JDom library for this purpose. It has a printer function, formatter options etc. http://www.jdom.org/