XMLEncoder (Java Platform SE 8 ) (original) (raw)

The XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean in the same way that the ObjectOutputStream can be used to create binary representation of Serializable objects. For example, the following fragment can be used to create a textual representation the supplied JavaBean and all its properties:

   XMLEncoder e = new XMLEncoder(
                      new BufferedOutputStream(
                          new FileOutputStream("Test.xml")));
   e.writeObject(new JButton("Hello, world"));
   e.close();

Despite the similarity of their APIs, the XMLEncoder class is exclusively designed for the purpose of archiving graphs of _JavaBean_s as textual representations of their public properties. Like Java source files, documents written this way have a natural immunity to changes in the implementations of the classes involved. The ObjectOutputStream continues to be recommended for interprocess communication and general purpose serialization.

The XMLEncoder class provides a default denotation for_JavaBean_s in which they are represented as XML documents complying with version 1.0 of the XML specification and the UTF-8 character encoding of the Unicode/ISO 10646 character set. The XML documents produced by the XMLEncoder class are:

Below is an example of an XML archive containing some user interface components from the swing toolkit:

frame1 0 0 200 200 Hello true

The XML syntax uses the following conventions:

Although all object graphs may be written using just these three tags, the following definitions are included so that common data structures can be expressed more concisely:

For more information you might also want to check outUsing XMLEncoder, an article in The Swing Connection.