Java, Software Development

Java – Convert JavaBean Using XMLEncoder and XMLDecoder

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources Convert LocalDateTime OffsetDateTime Run Codes Before Shutdown XML Tag Lambda PostgreSQL JDBC invoke JavaScript Applet SFTP Batch hang block main thread MySQL JDBC try-with-resources delete Unencrypted SoapFault Apache CXF Remove XML Element XSLT skip execute finally public static void main constructor fields Eclipse convert Iterator Stream StreamSupport XMLEncoder XMLDecoder rename P6Spy JDBC Example PDF Version JasperReports Run from Ant iReport Page Numbers Count entities persistence context hibernate

This post shows how to use the Java classes XMLEncoder and XMLDecoder to convert JavaBean objects to XML and back. Note that they support the specifications for JavaBeans to make things work. On the other hand, a conversion may not work if we use objects from Java classes that do not adhere to the JavaBean specification.

Convert a Java object to XML Using XMLEncoder

The following Java codes use the XMLEncoder class to convert a Java object to an XML document.

This will create an XML file with the file name of StudentPersisted.xml. On closer inspection, we can see that the XML has elements we did not expect, which may render our document non-portable when we use the document on platforms other than Java.

Moreover, on the off chance that we rename  StudentBean to something else, the XML document becomes invalid to XMLDecoder in the same codebase. The Java XMLDecoder may not convert an XML to an object we desire.

Convert XML to an object Using XMLDecoder

Suppose we have the following XML files and we want to convert its content to a Java object. To convert the XML, we will use the Java XMLDecoder class instead of the XMLEncoder.

Execute the following Java codes.

This outputs

This post is part of a reboot Java tutorial.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like