XML文件和Java对象转换是一件非常简单的事情,有了annotation的java文件和XML schema XSD文件,可以简单的通过JAXB API来实现XML与Java Object转换
marshaller Java to XML
Exception is not display here
prviate static javaxjaxbCtx = null;private static Schema schema = null;static {jaxbCtx = javax(T.class); //jaxbcontext is thread safeSchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // factory not thread safeSchema 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);javaxmarshaller = jaxbCtx.createMarshaller(); // not thread safemarshaller_ENCODING, “UTF-8”); marshaller_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 Javapublic 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实现出现错误时候系统行为,例如更细节的错误记录。
{……(SAXParseException ex) {logger.error(ex.getMessage());}(SAXParseException ex) {logger.error(ex.getMessage());}(SAXParseException ex) throws SAXException {throw ex;}}
人之相识,贵在相知;人之相知,贵在知心。