Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.ByteArrayOutputStream;
import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import javax.xml.validation.SchemaFactory;
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);

            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

            marshaller.marshal(object, sos);
            xmlFormOfBean = sos.toString();

        }
        return xmlFormOfBean;
    }
}