Story 2 of Java and XML: mutual conversion between XML and Java objects
Conversion Between XML files and Java objects is very simple. With annotation's java file and XML schema XSD file, you can use the jaxb api to convert XML and Java objects.
Marshaller Java to XML
Exception is not display here
prviate static javax.xml.bind.JAXBContext jaxbCtx = null;private static Schema schema = null;static {jaxbCtx = javax.xml.bind.JAXBContext.newInstance(T.class); //jaxbcontext is thread safeSchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // factory not thread safe Schema schema = sf.newSchema(new File("T.xsd")); //schema is thread safe}private static void validate(T t){ JAXBSource source = new JAXBSource(jaxbCtx, t); Validator validator = schema.newValidator(); // validator.setErrorHandler(new MyValidationErrorHandler()); validator.validate(source); // SAXException throws if failed, you can define your error handler or just notify the exception to caller}public static void marshToFile(T t, File file){ validate(t); javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller(); // not thread safe marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // if(logger.isDebugEnabled){ StringWriter sw = new StringWriter(); marshaller.marshal(t, sw); logger.debug(sw.toString());} marshaller.marshal( t, file);}
Unmarshaller XML to Java
public static T unmarshFromXml(File xmlFile){ Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); unmarshaller.setSchema(schema); //unmarshaller.setEventHandler(new MyValidationErrorHandler()); T test = (T) unmarshaller.unmarshal(xmlFile); //UnmarshalException if failed }
ErrorHandler
By default, SAXException is thrown. If a problem occurs during validation (fatal error), you can customize handler to implement system behavior when an error occurs, such as more detailed error records.
public class MyValidationErrorHandler implements ErrorHandler {...... public void warning(SAXParseException ex) { logger.error(ex.getMessage()); } public void error(SAXParseException ex) { logger.error(ex.getMessage()); } public void fatalError(SAXParseException ex) throws SAXException { throw ex; }}