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

52 篇文章 0 订阅
4 篇文章 0 订阅

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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值