Java – unmarshalling partial XML in XML schema

public class XmlPartialMarshaller<T> {
    private static final Logger LOGGER = LoggerFactory.getLogger(XmlPartialMarshaller.class);
    private DocumentBuilder documentBuilder;
    private DocumentBuilderFactory documentBuilderFactory;
    private Binder<Node> binderPartialXml;
    private JAXBContext contextPartialXml;

    private Class partialSchemaClass;

    public XmlPartialMarshaller(Class<T> partialSchemaClass) {
        this.partialSchemaClass = partialSchemaClass;

        try {
            this.documentBuilderFactory = DocumentBuilderFactory.newInstance();
            this.documentBuilder = documentBuilderFactory.newDocumentBuilder();

            this.contextPartialXml = JAXBContext.newInstance(partialSchemaClass);
            this.binderPartialXml = contextPartialXml.createBinder();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);

    public T marshalPartialXml(String xml) {
       try {
            InputStream inputStream = null;
            try {
                inputStream = IOUtils.toInputStream(xml);
                Document document = documentBuilder.parse(inputStream);
                Node xmlNode = document.getDocumentElement();
                JAXBElement<T> element = binderPartialXml.unmarshal(xmlNode,

                return element.getValue();
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            } finally {
                if (inputStream != null)
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);

        return null;
This entry was posted in Java, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s