码迷,mamicode.com
首页 > 编程语言 > 详细

Java与XML的故事二:XML与Java Object互相转换

时间:2015-03-08 00:11:39      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:jaxb   xsd   maven   

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

}

Java与XML的故事二:XML与Java Object互相转换

标签:jaxb   xsd   maven   

原文地址:http://blog.csdn.net/cloud_ll/article/details/43889441

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!