Java XML Parser

Using Dom4J

<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>

XMLParser.java

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;

import java.io.StringWriter;

public class XMLFormatter {
    private static Logger logger = LoggerFactory.getLogger(XMLFormatter.class);

    public static String formatXML(String xml) {
        if (xml != null && !StringUtils.isBlank(xml))
            try {
                Transformer transformer = TransformerFactory.newInstance()
                        .newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty(
                        "{http://xml.apache.org/xslt}indent-amount", "3");

                StreamResult streamResult = new StreamResult(new StringWriter());
                DOMSource domSource = new DOMSource(getDocument(xml));
                transformer.transform(domSource, streamResult);
                return streamResult.getWriter().toString();
            } catch (Exception e) {
                logger.error("Exception in formatting: " + e);
            }
        return xml;
    }

    private static Document getDocument(String input) {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputSource source = new InputSource(new StringReader(input));
            return documentBuilder.parse(source);
        } catch (Exception e) {
            logger.error("Exception in creating the document object for xml parsing: " + e);
        }
        return null;
    }

    public static String prettyPrint(String xml) {
        if (xml != null && !StringUtils.isBlank(xml)) {
            try {
                OutputFormat outputFormat = OutputFormat.createPrettyPrint();
                outputFormat.setIndent(true);
                outputFormat.setIndentSize(3);
                Document document = DocumentHelper.parseText(xml);
                StringWriter stringWriter = new StringWriter();
                XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat);
                xmlWriter.write(document);
                return stringWriter.toString();
            } catch (Exception e) {
                logger.error("Error in formatting xml: " + e);
            }
        }
        return xml;
    }
    public static String unPrettyPrint(String xml) {
        if (xml != null && !StringUtils.isBlank(xml)) {
            try {
                OutputFormat outputFormat = OutputFormat.createCompactFormat();
                Document document = DocumentHelper.parseText(xml);
                StringWriter stringWriter = new StringWriter();
                XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat);
                xmlWriter.write(document);
                String outcome = stringWriter.toString();
                if(containsMoreTrailing(outcome)){
                    return outcome.replace("\n", "").replace("\t", "").replace("\r", "");
                }else{
                    return outcome;
                }
            } catch (Exception e) {
                logger.error("Error in formatting xml: " + e);
            }
        }
        return xml;
    }

    private static boolean containsMoreTrailing(String input){
        return input.contains("\n") || input.contains("\t") || input.contains("\r");
    }
}

XMLParser Test

import org.junit.Test;

import static org.junit.Assert.*;

public class XMLFormatterTest {
    private final static String RAW_UNFORMATTED_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Response xmlns=\"http://xxxxrmi.xxxx.com/wmqcontracts\"><Header><receiverId>xxxx.Backend</receiverId><senderId>.Backend</senderId><messageType>RMIORDRSP</messageType><messageTypeVersion>1.0</messageTypeVersion></Header><RMIORDRSP OrderNo=\"000746\" OrderId=\"82d2c88f-21e7-4375-af69-40aea1c7d8a3\" Status=\"EXECUTED\"><OrderLines><OrderLine LineNo=\"1\" PartNo=\"RMI2\" Quantity=\"1.0\" Status=\"EXECUTED\"/></OrderLines></RMIORDRSP></Response>";
    String RAW_FORMATTED_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Response xmlns=\"http://xxxxrmi.xxxx.com/wmqcontracts\"><Header><receiverId>Backend</receiverId><senderId>.Backend</senderId><messageType>RMIORDRSP</messageType>\n" +
            "<messageTypeVersion>1.0</messageTypeVersion>\n" +
            "</Header>\n" +
            "<RMIORDRSP OrderNo=\"000746\" OrderId=\"82d2c88f-21e7-4375-af69-40aea1c7d8a3\" Status=\"EXECUTED\">\n" +
            "\t<OrderLines>\n" +
            "\t\t<OrderLine LineNo=\"1\" PartNo=\"RMI2\" Quantity=\"1.0\" Status=\"EXECUTED\"/>\n" +
            "\t</OrderLines>\n" +
            "</RMIORDRSP>\n" +
            "</Response>";

    @Test
    public void testNativeFormatUnformattedXML(){
        String actual = XMLFormatter.formatXML(RAW_UNFORMATTED_XML);
        assertNotNull(actual);
    }
    @Test
    public void testNativeFormatNull(){
        String actual = XMLFormatter.formatXML(null);
        assertNull(actual);
    }
    @Test
    public void testNativeFormatEmpty(){
        String actual = XMLFormatter.formatXML("");
        assertNotNull(actual);
        assertTrue(actual.equals(""));
    }

    @Test
    public void testUnFormattedXMLFormat() {
        final String actual = XMLFormatter.prettyPrint(RAW_UNFORMATTED_XML);
        assertNotNull(actual);
        assertTrue(actual.contains("\n"));
    }

    @Test
    public void testNullXMLFormat() {
        final String actual = XMLFormatter.prettyPrint(null);
        assertNull(actual);
    }

    @Test
    public void testEmptyXMLFormat() {
        final String actual = XMLFormatter.prettyPrint("");
        assertNotNull(actual);
        assertTrue(actual.equals(""));
    }

    @Test
    public void testFormattedXMLFormat() {
        final String actual = XMLFormatter.unPrettyPrint(RAW_FORMATTED_XML);
        assertNotNull(actual);
        assertFalse(actual.contains("\n"));
    }

    @Test
    public void testNullUnprettyXMLFormat() {
        final String actual = XMLFormatter.unPrettyPrint(null);
        assertNull(actual);
    }

    @Test
    public void testEmptyUnprettyXMLFormat() {
        final String actual = XMLFormatter.unPrettyPrint("");
        assertNotNull(actual);
        assertTrue(actual.equals(""));
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *