Java HTML / XML How to - Handle Unmarshaller Event








Question

We would like to know how to handle Unmarshaller Event.

Answer

import java.io.File;
/*  ww w  .  j  ava 2s. com*/
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.stream.Location;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stream.StreamSource;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Customer.class);

    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(new File(
        "input.xml")));

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    unmarshaller.setListener(new LocationListener(xsr));
    Customer customer = (Customer) unmarshaller.unmarshal(xsr);
  }

  @XmlRootElement
  public static class Customer {

    private String name;
    private Address address;

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public Address getAddress() {
      return address;
    }

    public void setAddress(Address address) {
      this.address = address;
    }

  }

  public static class Address {

    private String street;

    public String getStreet() {
      return street;
    }

    public void setStreet(String street) {
      this.street = street;
    }

  }
}

class LocationListener extends Unmarshaller.Listener {

  private XMLStreamReader xsr;

  public LocationListener(XMLStreamReader xsr) {
    this.xsr = xsr;
  }

  @Override
  public void afterUnmarshal(Object target, Object parent) {
    log("End", target);
  }

  @Override
  public void beforeUnmarshal(Object target, Object parent) {
    log("Start", target);
  }

  private void log(String event, Object target) {
    System.out.print(event);
    System.out.print(" ");
    System.out.print(target);
    System.out.print(" [");
    Location location = xsr.getLocation();
    System.out.print(location.getLineNumber());
    System.out.print(",");
    System.out.print(location.getColumnNumber());
    System.out.println("]");
  }

}

input.xml

<?xml version="1.0" encoding="UTF-8"?>
<customer>
    <name>Jane Doe</name>
    <address>
        <street>1 A Street</street>
    </address>
</customer>