Java HTML / XML How to - Use Unmarshaller and schema in JAXB








Question

We would like to know how to use Unmarshaller and schema in JAXB.

Answer

import java.io.FileInputStream;
/*from w  w  w  .j  a v a  2  s.  c  o m*/
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

public class Main {

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

    XMLInputFactory xif = XMLInputFactory.newInstance();
    FileInputStream fis = new FileInputStream("input.xml");
    XMLStreamReader xsr = xif.createXMLStreamReader(fis);
    xsr.nextTag();
    String noNamespaceSchemaLocation = xsr.getAttributeValue(
        XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,
        "noNamespaceSchemaLocation");
    System.out.println(noNamespaceSchemaLocation);

    Unmarshaller um = context.createUnmarshaller();
    User response = (User) um.unmarshal(xsr);
  }
}

class User {
}