Java, Software Development

Java – Convert JavaBean Using XMLEncoder and XMLDecoder

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.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like