天天看點

Java與XML的故事二:XML與Java Object互相轉換

XML檔案和Java對象轉換是一件非常簡單的事情,有了annotation的java檔案和XML schema XSD檔案,可以簡單的通過JAXB API來實作XML與Java Object轉換

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 safe
SchemaFactory 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

預設抛出SAXException如果在validation的時候出現問題(fatal error),可以自己定制handler實作出現錯誤時候系統行為,例如更細節的錯誤記錄。

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;
    }

}
           

繼續閱讀