Java 2EE and XML Development

Скачать в pdf «Java 2EE and XML Development»


Table 2.8 Core Long Term JavaBeans Persistence classes


Class name


Description


java.beans.XMLEncoder


Serializes a JavaBean as XML to an output stream.


java.beans.XMLDecoder


Reads in a JavaBean as XML from an input stream.

Writing a JavaBean to XML


As an example, let us define a simple JavaBean with one property, as follows:


public class SimpleJavaBean { private String name;


public SimpleJavaBean(String name) { setName(name);


}


// accessor


public String getName() { return name; }


// modifier


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


}


As you can see, this bean implements the JavaBeans contract of providing an accessor and modifier for its single property. We can save this bean to an XML file named simple.xml using the following code snippet:


import java.beans.XMLEncoder; import java.io.*;


XMLEncoder e


= new XMLEncoder(new BufferedOutputStream(


new FileOutputStream(«simple.xml»))); e.writeObject(new SimpleJavaBean(«Simpleton»)); e.close();


The code above creates an XMLEncoder on top of a java.io.BufferedOutput-Stream representing the file simple.xml. We then pass the SimpleJavaBean instance reference to the encoder’s writeObject method and close the stream. The resulting file contents are as follows:


<?xml version=»1.0″ encoding=»UTF-8″?>


<java version=»1.0″ class=»java.beans.XMLDecoder»>


<object class=»SimpleJavaBean»>


<void property=»name»>


<string>Simpleton</string>


</void>


</object>


</java>


We will not cover the XML syntax in detail, since you do not need to understand it to use this API. Detailed information about this syntax is available in the specification, should you need it.

Скачать в pdf «Java 2EE and XML Development»