xmlToBean
/**
* Convert XML to Bean with Schema Validation.
*
* @param entityClass entity Class
* @param entity XML
* @return entity object
* @throws JAXBException JAXB Exception
*/
public static <T> Object xmlToBean(Class<T> 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 <T> Marshaller newMarshaller(Class<T> 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);