Introduction Example Serialexable

Example

Here is a simple example class that can be converted to XML (marshalled).

public class Pojo {

  private String str;
  private boolean bool;

  public String getStr() {
    return str;
  }

  public void setStr(String str) {
    this.str = str;
  }

  public boolean isBool() {
    return bool;
  }

  public void setBool(boolean bool) {
    this.bool = bool;
  }

}

To marshal this, call Marshaller.marshal() with the object to convert.

  Pojo pojo = new Pojo();
  pojo.setStr("test");
  pojo.setBool(true);
  try {
    String xml = Marshaller.marshal(pojo);
    System.out.println(xml);
  } catch (MarshalException e) {
    e.printStackTrace();
  }

This will produce an XML representation of the object:

  <?xml version="1.0" encoding="UTF-8"?>
  <root type="net.sf.serialex.example.Pojo">
    <field name="str" type="java.lang.String"><![CDATA[test]]></field>
    <field name="bool" type="boolean" value="true" />
  </root>

To convert XML back to a Java object (unmarshal), call Unmarshaller.unmarshal() with the class of the required object and the XML.

  try {
    Pojo reconstitutedPojo = Unmarshaller.unmarshal(Pojo.class, xml);
  } catch (UnmarshalException e) {
    e.printStackTrace();
  }

You can also discover the class of object to be unmarshalled.

  try {
    Class clazz = Unmarshaller.unmarshalClass(xml);
  } catch (UnmarshalException e) {
    e.printStackTrace();
  }