diff --git a/README.md b/README.md index c769d54..320d689 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,12 @@ String xml = XmlUtils.objectToXml(myObject); ``` +Object to pretty printed XML + +```java +String prettyPrinted = XmlUtils.prettyPrint(myObeject); +``` + XML to Object ```java diff --git a/src/main/java/com/ljunggren/xmlUtils/XmlUtils.java b/src/main/java/com/ljunggren/xmlUtils/XmlUtils.java index 3473e63..3fc04b7 100644 --- a/src/main/java/com/ljunggren/xmlUtils/XmlUtils.java +++ b/src/main/java/com/ljunggren/xmlUtils/XmlUtils.java @@ -2,12 +2,23 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class XmlUtils { public static String objectToXml(Object object) throws JsonProcessingException { - return new XmlMapper().writeValueAsString(object); + return objectToXml(object, new XmlMapper()); + } + + public static String prettyPrint(Object object) throws JsonProcessingException { + XmlMapper mapper = new XmlMapper(); + mapper.enable(SerializationFeature.INDENT_OUTPUT); + return objectToXml(object, mapper); + } + + private static String objectToXml(Object object, XmlMapper mapper) throws JsonProcessingException { + return mapper.writeValueAsString(object); } public static T xmlToObject(String xml, Class clazz) throws JsonMappingException, JsonProcessingException { diff --git a/src/test/java/com/ljunggren/xmlUtils/XmlUtilsTest.java b/src/test/java/com/ljunggren/xmlUtils/XmlUtilsTest.java index 59fdca7..b67e013 100644 --- a/src/test/java/com/ljunggren/xmlUtils/XmlUtilsTest.java +++ b/src/test/java/com/ljunggren/xmlUtils/XmlUtilsTest.java @@ -33,6 +33,17 @@ } @Test + public void prettyPrintTest() throws JsonProcessingException { + User user = new User("Alex", 40, true); + String expected = "\r\n" + + " Alex\r\n" + + " 40\r\n" + + "\r\n"; + String actual = XmlUtils.prettyPrint(user); + assertEquals(expected, actual); + } + + @Test public void xmlToObjectTest() throws JsonMappingException, JsonProcessingException { User user = new User("Alex", 40, true); String xml = XmlUtils.objectToXml(user);