Java tutorial
//package com.java2s; import java.io.ByteArrayOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.namespace.QName; import org.xml.sax.SAXException; public class Main { /** * Generic method to Validate XML file while marshalling against their schema. * * @param context * @param schemaFile * @param object * @return * @throws SAXException * @throws JAXBException */ public static String validateAndMarshallXML(JAXBContext context, String schemaFile, Object object) throws SAXException, JAXBException { String xmlFormOfBean = null; // if (context != null && (schemaFile != null && schemaFile.trim().length() > 0)) { Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); QName qname = new QName("www.genpact.com", "CobCmData"); marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "www.genpact.com cob_cm.xsd "); // SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // thread- safe // marshaller.setSchema(sf.newSchema(new File(schemaFile))); // validate jaxb context against schema ByteArrayOutputStream sos = new ByteArrayOutputStream(); // for XML output into string // JAXBElement<CobCmData> rootElement = new JAXBElement<CobCmData>(qname,CobCmData.class,(CobCmData)object); // marshaller.marshal(rootElement, sos); // xmlFormOfBean = sos.toString(); // } return xmlFormOfBean; } }