XML file and Java Object Conversion is a very simple thing, with annotation java files and XML Schema XSD files, you can easily through the JAXB API to implement XML and Java Object conversion
Marshaller Java to XML
Exception is isn't display here
Prviate Static Javax. XML. Bind. JaxbcontextJaxbctx = null;private static Schema schema = null;static {Jaxbctx = Javax. XML. Bind. Jaxbcontext. newinstance(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);Javax. XML. Bind. MarshallerMarshaller = Jaxbctx. Createmarshaller();//not thread safeMarshaller. 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
publicstaticunmarshFromXml(File xmlFile){ Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); unmarshaller.setSchema(schema); //unmarshaller.setEventHandler(new MyValidationErrorHandler()); //UnmarshalException if failed }
ErrorHandler
Default throw Saxexception If there is a problem with validation (fatal error), you can customize the handler to implement the system behavior when the error occurs, such as more detailed error logging.
public class myvalidationerrorhandler implements errorhandler {...... public void warning (Saxparseexception ex) {Logger.error (Ex.getmessage ()); } public void error< /span> (Saxparseexception ex) {Logger.error (Ex.getmessage ()); } public void FatalError (saxparseexception ex) throws saxexception {throw ex; }}
Story Two of Java and XML: XML and Java object Convert to each other