Lightweight XML Protocol Binder
It is common nowadays to design application protocols using XML. In some cases these are based on standard DTDs or Schemas such as SOAP, the various content syndication schemes, etc. Often, however, they are application specific, and the decision to utilize XML is made after consideration of other approaches, such as Java serialization, or even custom binary protocols.
Once the decision to use XML is taken, the central problem is the transformation of data between internal structures such as Java objects, and a character stream containing an XML document. A developer might choose to use the DOM directly, creating root documents, element nodes, attribute nodes etc. in an ad hoc manner. This can be tedious and time consuming, and if not carefully managed, can lead to real headaches with code bloat and its attendant maintenance problems.For complex document structures based on the full XML specification, utilizing features such as namespaces, mixed content, etc., implementations of the JAXB specification provide one approach to a systematic and clean design.
In a nutshell, JAXB provides:
- Binding, to read an XML schema, and generate a set of Java classes, one per element defined in the schema.
- Marshalling, to transform a tree of objects into an XML document
- Unmarshalling, to read an XML document and generate the corresponding object tree.
You can learn more about JAXB here.
Sometimes, however, a protocol may be designed using only a minimal set of XML features. In such cases, JAXB may be overkill, particularly if developers are not sufficiently familiar with the XML Schema specification.
Several years ago I was asked for help in cleaning up a project that had become bogged down in debugging and maintenance problems. Because of the minimal subset of XML features present in the message formats, I proposed a solution situated in the middle ground between the complexity of JAXB and the anarchy of the DOM. (JAXB was also very new at the time, and the documentation was not yet up to Sun's usual standard.) The result was the "Simple XML Protocol Binder". As always before coding any non-trivial project, I created a detailed design document, which you can view here.