1. 2015-09-29 - Pretty print an XML document in Java; Tags: Pretty print an XML document in Java
    Loading...

    Pretty print an XML document in Java

    If you want to have a pretty printed output of a XML tree, following snippet may be of interest to you.

    import java.io.StringWriter;
    import java.nio.charset.StandardCharsets;
    import org.w3c.dom.DOMConfiguration;
    import org.w3c.dom.DOMImplementation;
    import org.w3c.dom.Document;
    import org.w3c.dom.ls.DOMImplementationLS;
    import org.w3c.dom.ls.LSOutput;
    import org.w3c.dom.ls.LSSerializer;
    /**
     * Test util for debugging and handling of {@link Document}}
     */
    public final class DocumentUtils {
        private static final String FORMAT_PRETTY_PRINT = "format-pretty-print";
        /**
         * prevent instantiation
         */
        private DocumentUtils() {
            //nth.
        }
        /**
         * Prints a DOM document to XML using DOM Load and Save's LSSerializer.
         * @param doc
         * @return xml output
         * @see LSSerializer
         */
        public static final String getStringFromDoc(org.w3c.dom.Document doc) {
            DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
            LSSerializer lsSerializer = domImplementation.createLSSerializer();
            return lsSerializer.writeToString(doc);
        }
        /**
         * Pretty-prints a DOM document to XML using DOM Load and Save's LSSerializer.
         * Note that the "format-pretty-print" DOM configuration parameter can only be set in JDK 1.6+.
         * @param doc
         * @return formatted xml output
         * @see LSSerializer
         * @see LSOutput
         * @see DOMConfiguration
         */
        public static final String getPrettyPrintedStringFromDoc(org.w3c.dom.Document doc) {
            DOMImplementation domImplementation = doc.getImplementation();
            if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
                DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation.getFeature("LS", "3.0");
                LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
                DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
                if (domConfiguration.canSetParameter(FORMAT_PRETTY_PRINT, Boolean.TRUE)) {
                    lsSerializer.getDomConfig().setParameter(FORMAT_PRETTY_PRINT, Boolean.TRUE);
                    LSOutput lsOutput = domImplementationLS.createLSOutput();
                    lsOutput.setEncoding(StandardCharsets.UTF_8.name());
                    StringWriter stringWriter = new StringWriter();
                    lsOutput.setCharacterStream(stringWriter);
                    lsSerializer.write(doc, lsOutput);
                    return stringWriter.toString();
                } else {
                    throw new UnsupportedOperationException("DOMConfiguration 'format-pretty-print' parameter isn't settable.");
                }
            } else {
                throw new UnsupportedOperationException("DOM 3.0 LS and/or DOM 2.0 Core not supported.");
            }
        }
    }
    

    Can be used like this:

    @Test
    public void testGetStringFromDoc() throws Exception {
    	// arrange
    	Document document = DocumentUtils.createEmptyDocument();
    	// act
    	Element customer = document.createElement("id");
    	customer.setTextContent("4711");
    	document.appendChild(customer);
    	String actual = DocumentUtils.getPrettyPrintedStringFromDoc(document);
    	// assert
    	assertEquals("Generated xml is equals.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<id>4711</id>", actual.trim());
    }
    
  2. 2015-09-29 - Create a XML or HTML document; Tags: Create a XML or HTML document
    Loading...

    Create a XML or HTML document

    Using in Java the Document Object Model (DOM). This post contains a snippet to create XML document object.

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    

    To create an XML document from String input

    /**
     * Create document from String
     * @param xml
     * @return
     * @throws Exception
     */
    public static Document createDocumentFromXMLString(String xml) {
    	try {
    		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    		factory.setNamespaceAware(true);
    		DocumentBuilder builder = factory.newDocumentBuilder();
    		return builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
    	} catch (ParserConfigurationException | IOException | SAXException e) {
    		LOGGER.error("Could not create document for input {}", xml, e);
    	}
    	return null;
    }