ProblemYou want to generate XML directly from Java objects. SolutionUse the XML Object Serializers. DiscussionThe 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.javaimport 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( ); } } |