Story 2 of Java and XML: mutual conversion between XML and Java objects

Source: Internet
Author: User

Story 2 of Java and XML: mutual conversion between XML and Java objects

Conversion Between XML files and Java objects is very simple. With annotation's java file and XML schema XSD file, you can use the jaxb api to convert XML and Java objects.

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 safeSchemaFactory 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

By default, SAXException is thrown. If a problem occurs during validation (fatal error), you can customize handler to implement system behavior when an error occurs, such as more detailed error records.

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.