In current software development world, serializing object to some human readable format such as "XML", "JSON" is quite common.
In this post I will show you a small code snippet for encoding Java Object to XML and decoding XML to Java Object only using Java Standard API.
I think this approach is suitable if you need to quick and simple solution to encoding and decoding java object to XML string.
Actually code is very simple. Please see the code below :)
If you need to input or output XML to file, you should pass FileOutputStream or FileInputStream instead of ByteArrayOutputStream or ByteArrayInputStream.
package com.dukesoftware.utils.xml; import java.beans.XMLDecoder; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; public class XMLUtils { public final static Object decodeToXML(String file) throws FileNotFoundException{ try(XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(file)))){ return decoder.readObject(); } } public final static Object decodeToXML(String xmlStr) { try(XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(xmlStr.getBytes()))){ return decoder.readObject(); } } }}
Below is the test code for decodeToXML, decodeToXML method
package com.dukesoftware.utils.xml; import java.io.File; import java.util.HashSet; import org.junit.Assert; import org.junit.Test; public class XMLUtilsTest { @Test public void testEncodeAndDecodeString() throws Exception { // object which will be encoded to XML HashSet<String> sourceObj = new HashSet<>(); sourceObj.add("A"); sourceObj.add("B"); sourceObj.add("C"); // Encode to XML String xmlStr = XMLUtils.encodeToXML(sourceObj); // Debug print for XML String System.out.println(xmlStr); // Decode to Object from the XML String generated in above process HashSet<String> decodedFromXML = (HashSet<String>)XMLUtils.decodeToXML(xmlStr); // Assertion Assert.assertEquals(sourceObj.size(), decodedFromXML.size()); for(String e : sourceObj){ Assert.assertTrue(decodedFromXML.contains(e)); } } }
If you execute above test, you should see XML String below in standard output.
<?xml version="1.0" encoding="UTF-8"?> <java version="1.8.0" class="java.beans.XMLDecoder"> <object class="java.util.HashSet"> <void method="add"> <string>A</string> </void> <void method="add"> <string>B</string> </void> <void method="add"> <string>C</string> </void> </object> </java>
コメント