Java使用JAXB对xml的解析和转换

xmlToBean

    /**
     * Convert XML to Bean with Schema Validation.
     *
     * @param entityClass entity Class
     * @param entity      XML
     * @return entity object
     * @throws JAXBException JAXB Exception
     */
    public static  Object xmlToBean(Class entityClass, String entity, Schema schema) throws JAXBException {
        Unmarshaller unMarshaller = JAXBContext.newInstance(entityClass).createUnmarshaller();
        unMarshaller.setSchema(schema);
        return unMarshaller.unmarshal(new StringReader(entity));
    }

   

beanToXml

     /**
     * Convert Bean to XML and Validate the XML with Schema.
     *
     * @param entity entity object
     * @return XML
     * @throws JAXBException JAXB Exception
     */
    public static String beanToXml(Marshaller marshaller, Object entity, Schema schema) throws JAXBException {
        StringWriter writer = new StringWriter();
        marshaller.setSchema(schema);
        marshaller.marshal(entity, writer);
        return writer.toString();
    }

    /**
     * Create Marshaller
     *
     * @param entityClass entity object Class
     * @return Marshaller
     * @throws JAXBException JAXB Exception
     */
    public static  Marshaller newMarshaller(Class entityClass) throws JAXBException {
        Marshaller marshaller = newJaxbContext(entityClass).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        return marshaller;
    }

Example:

xml to bean

 URL xsdUrl = this.getClass().getResource("xxx.xsd");
 Schema schema = factory.newSchema(xsdUrl);
 Xxbean xxbean = (Xxbean) XmlAndBeanUtil.xmlToBean(Xxbean.class, xmlString, schema);

 

bean to xml

 Marshaller marshaller = XmlAndBeanUtil.newMarshaller(Xxbean.class);
 marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "Xxbean.xsd");
 String xml = XmlAndBeanUtil.beanToXml(marshaller, xxbean, null);

 

你可能感兴趣的:(Java)