Friday, October 31, 2008

XML Data Binding and Serialization Java

When working with XML data, there are a number of libraries that can be used, depending on the complexity of your needs.

For a once off reading of an XML file, you can just use a SAX/DOM based parser, such as those defined in the javax.xml.parsers.

If you want to get a particular element or attrbute out of an XML document, then you can use the javax.xml.xpath library to parse the document. This makes it easy to quickly find a single element, or set of elements in an XML document.

If you want to do something more heavyweight, and you are going to use a particular XML schema repeatedly, then you will probably need have some sort of binding/marshalling libraries. Binding refers to the action of taking an XML schema and automatically making a set of classes that correspond to the schema. Marshalling goes the opposite way and creates an XML file from a class. Note that to marshall an object, you don't necessarily need to have bound it previously. You can just declare any old class and marshall it.

The most common binging/marshalling library is JAXB (javax.xml.bind.JAXB). This includes a tool for automatically binding an XML schema to a set of classes, as well as a Marshaller that will create XML from the created objects.

If you just want to marshall an object, then there are libraries, such as XStream, that make this very simple. Just create any old object, and use XStream to define/create an XML document for it. It is a quick and easy solution, especially if you want to define your own classes to hold the XML data (instead of going down the automatic binding route).

No comments: