Developing JAXB Applications Using EclipseLink MOXy, Release 2.6
  Go To Table Of Contents

Binding to an Existing Document

The JAXB Binder interface (introduced in JAXB 2.0) allows you to preserve an entire XML document, even if only some of the items are mapped.

Normally, when using an Unmarshaller to load the XML document into objects, and a Marshaller to save the objects back to XML, the unmapped content will be lost.

A Binder can be created from the JAXBContext to interact with the XML in the form of a DOM. The Binder maintains an association between the Java objects and their corresponding DOM nodes.

Example 2-31 Using a Binder

import javax.xml.bind.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.*;
public class BinderDemo {
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        File xml = new File("input.xml");
        Document document = db.parse(xml);
        JAXBContext jc = JAXBContext.newInstance(Customer.class);
        Binder<Node> binder = jc.createBinder();
        Customer customer = (Customer) binder.unmarshal(document);
        customer.getAddress().setStreet("2 NEW STREET");
        PhoneNumber workPhone = new PhoneNumber();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(document), new StreamResult(System.out));

The Binder applies the changes to the original DOM instead of creating a new XML document, thereby preserving the entire XML infoset.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <name>Jane Doe</name>
    <!-- COMMENT #1 -->
        <street>2 NEW STREET</street>
        <!-- COMMENT #2 -->
        <city>Any Town</city>
    <!-- COMMENT #3 -->
    <phone-number type="home">555-HOME</phone-number>
    <!-- COMMENT #4 -->
    <phone-number type="cell">555-CELL</phone-number>
    <phone-number type="work">555-WORK</phone-number>
    <!-- COMMENT #5 -->