Recipe 21.1 Generating XML from Objects


Problem

You want to generate XML directly from Java objects.

Solution

Use the XML Object Serializers.

Discussion

The Serialization demonstration in Recipe 10.18 showed an abstract base class that called upon abstract methods to write the file out in some format. Example 21-1 is the XML subclass for it.

Example 21-1. SerialDemoXML.java
import java.beans.XMLDecoder; import java.io.*; /** Show the XML serialization added to "java.beans.*" in JDK1.4.  * Subclass "SerialDemoAbstractBase" to get most of the infrastructure  */ public class SerialDemoXML extends SerialDemoAbstractBase {     public static final String FILENAME = "serial.xml";     public static void main(String[] args) throws IOException {         new SerialDemoXML( ).save( );         new SerialDemoXML( ).dump( );     }     /** Save the data to disk. */     public void write(Object theGraph) throws IOException {         XMLEncoder os = new XMLEncoder(        // NEEDS JDK 1.4             new BufferedOutputStream(                 new FileOutputStream(FILENAME)));         os.writeObject(theGraph);         os.close( );     }     /** Display the data */     public void dump( ) throws IOException {         XMLDecoder inp = new XMLDecoder(        // NEEDS JDK 1.4             new BufferedInputStream(                 new FileInputStream(FILENAME)));         System.out.println(inp.readObject( ));         inp.close( );     } }



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net