javaxmlxml-serializationstaxwoodstox

How do I serialize / deserialize a class in XML with Woodstox StAX 2


I'm pretty much trying to archive, what has been done in how-to-serialize-deserialize-simple-classes-to-xml-and-back (C#) in Java. If possible, I would like to avoid writing a serialize / deserialize methods for each class.

For example, part of serialize:

    XMLOutputFactory xof = null;
    XMLStreamWriter2 writer = null;

    try {
        resp.setContentType("text/plain");
        xof = XMLOutputFactory.newInstance();
        writer = (XMLStreamWriter2) //
        xof.createXMLStreamWriter(resp.getOutputStream());

        writer.writeStartDocument("1.0");
        writer.writeStartElement("data");
        // 
        // Magic happens here.
        //
        writer.writeEndElement();
        writer.writeEndDocument();
    } catch (XMLStreamException e) {
        e.printStackTrace();
        resp.sendError(1, "Problem 1 occured.");
    } finally {
        try {
            writer.flush();
            writer.close();
        } catch (XMLStreamException e) {
            e.printStackTrace();
            resp.sendError(2, "Problem 2 occured.");
        }
    }

Not part of this question, as I'm trying to tackle problems 1 by 1, but might give you a sense of what I'm trying to do. When I deserialize, I would also like to check if the input is valid. Eventually I want to use XSLT transforms with serialized form.


Solution

  • JAXB is how you serialize Java objects to XML. The following will help you get started:

    JAXB Implementations

    There are several implementations of this standard:

    Woodstox StAX 2

    JAXB accepts many input/output formats including StAX.

    Validation

    XML is converted to objects using an Unmarshaller, and objects are converted to XML with a Marshaller. You can set an instance of javax.xml.validation.Schema to validate the input during these operations.

    You can also use the javax.xml.validation APIs directly with JAXB, check out the following for an example:

    XSLT

    The javax.xml.transform libraries are used in Java to perform XSLT transforms. JAXB is designed to work with these libraries using JAXBSource and JAXBResult.

    For More Information

    Check out my blog: