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;
}
}
时间: 2024-10-14 00:21:11