How do I convert an XML persistence to Java Bean?

In the previous example you can see how to convert a bean into an XML persistence. Now we’ll do the opposite, converting the XML back to a bean. For the BeanToXML class use in this example please refer to How do I convert a bean to XML persistence? example.

package org.kodejava.bean;

import java.beans.XMLDecoder;
import java.util.Objects;

public class XmlToBean {
    public static void main(String[] args) {
        XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(

        // Reads the next object from the underlying input stream.
        BeanToXML bean = (BeanToXML) decoder.readObject();

        System.out.println("ID              = " + bean.getId());
        System.out.println("Item Name       = " + bean.getItemName());
        System.out.println("Item Colour     = " + bean.getItemColour());
        System.out.println("Item Quantities = " + bean.getItemQuantities());

Here is our Bean.xml persistence file:

<?xml version="1.0" encoding="UTF-8"?>
<java version="17" class="java.beans.XMLDecoder">
    <object class="org.kodejava.bean.BeanToXML">
        <void property="id">
        <void property="itemColour">
            <string>Dark Red</string>
        <void property="itemName">
        <void property="itemQuantities">

The result are:

ID              = 1
Item Name       = T-Shirt
Item Colour     = Dark Red
Item Quantities = 100

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.