Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

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

import javax.xml.bind.Unmarshaller;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> Object xmlToObject(String xmlContent, Class<T> clazz) throws JAXBException {

        ByteArrayInputStream xmlContentBytes = new ByteArrayInputStream(xmlContent.getBytes());
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(null); //note: setting schema to null will turn validator off
        Object unmarshalledObj = unmarshaller.unmarshal(xmlContentBytes);
        Object xmlObject = clazz.cast(unmarshalledObj);

        return (T) xmlObject;
    }

    @SuppressWarnings("unchecked")
    public static <T> Object xmlToObject(InputStream xmlContent, Class<T> clazz) throws JAXBException {

        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(null); //note: setting schema to null will turn validator off
        Object unMarshalled = unmarshaller.unmarshal(xmlContent);
        Object xmlObject = clazz.cast(unMarshalled);

        return (T) xmlObject;
    }
}