/java/

Convert POJO to XML without Annotations

2015-06-27 13:01:37

Based on: Adam Bien - Writing POJOs To XML Without Annotations

My test:

package btbw.pl;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class BeeApp {

    public static void main(String [] args) {
        try {

            XMLEncoder encoder = new XMLEncoder(new FileOutputStream(new File("/tmp/bee.xml")));
            encoder.writeObject(new Bee("Michal", "A"));
            encoder.close();

            XMLDecoder decoder = new XMLDecoder(new FileInputStream(new File("/tmp/bee.xml")));
            Bee bee = (Bee) decoder.readObject();

            System.out.println("Bee: " + bee);
            System.out.println("Bee Name: " + bee.getName());
            System.out.println("Bee Type: " + bee.getType());

            new File("/tmp/bee.xml").delete();

        } catch (FileNotFoundException e) {
            System.out.println("Problem with encoder: " + e.getMessage());
        }
    }

}
package btbw.pl;

public class Bee {

    private String name;
    private String type;

    public Bee(String name, String type) {
        this.name = name;
        this.type = type;
    }

    public Bee() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Bee{" +
                "name='" + name + '\'' +
                ", type='" + type + '\'' +
                '}';
    }
}

pom.xml

<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>

<project http:="" maven-4.0.0.xsd&quot;="" maven.apache.org="" xmlns='"http://maven.apache.org/POM/4.0.0"' xmlns:xsi='"http://www.w3.org/2001/XMLSchema-instance"' xsd="" xsi:schemalocation='"http://maven.apache.org/POM/4.0.0'>
<modelversion>4.0.0</modelversion>
<groupid>btbw.pl</groupid>
<artifactid>xmlpojo</artifactid>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
</project>