Deserializing a Bean from XML - Java Object Oriented Design

Java examples for Object Oriented Design:Java Bean

Description

Deserializing a Bean from XML

Demo Code



import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Main {
  public static void main(String[] args) throws Exception {
    try {/* w w w. ja v  a  2 s  .c om*/
      XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(
          new FileInputStream("infilename.xml")));

      MyClass o = (MyClass) decoder.readObject();
      decoder.close();

      // Use the object
      int prop = o.getProp(); // 1
      int[] props = o.getProps(); // [1, 2, 3]
    } catch (FileNotFoundException e) {
    }
  }
}

class MyClass{
  int prop;
  int[] props;
  public int getProp() {
    return prop;
  }
  public void setProp(int prop) {
    this.prop = prop;
  }
  public int[] getProps() {
    return props;
  }
  public void setProps(int[] props) {
    this.props = props;
  }
  
}

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.0" class="java.beans.XMLDecoder">
    <object class="MyClass">
        <void property="prop">
            <int>1</int>
        </void>
        <void property="props">
            <array class="int" length="3">
                <void index="0">
                    <int>1</int>
                </void>
                <void index="1">
                    <int>2</int>
                </void>
                <void index="2">
                    <int>3</int>
                </void>
            </array>
        </void>
    </object>
</java>

Related Tutorials