com.aeontronix.commons.xml.jaxb.JAXBUtils Maven / Gradle / Ivy
The newest version!
package com.aeontronix.commons.xml.jaxb;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class JAXBUtils {
/**
* Create a JAXB Unmarshaller for the specific object
*
* @param objClass Object Class
* @return JAXB Unmarshaller
* @throws JAXBException If an error occurs creating unmarshaller
*/
public static Unmarshaller createJAXBUnmarshaller(Class objClass) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(objClass);
return jaxbContext.createUnmarshaller();
}
/**
* Convert a XML document to an object using JAXB.
* This will automatically convert a context based on the object's class package
*
* @param objClass JAXB object class
* @param xmlInputStream xml input stream
* @return JAXB object
*/
public static X xmlToObj(Class objClass, InputStream xmlInputStream) throws JAXBException {
Unmarshaller unmarshaller = createJAXBUnmarshaller(objClass);
return objClass.cast(unmarshaller.unmarshal(xmlInputStream));
}
/**
* Convert a XML document to an object using JAXB.
* This will automatically convert a context based on the object's class package
*
* @param objClass JAXB object class
* @param xmlFile XML File
* @return JAXB object
*/
public static X xmlToObj(Class objClass, File xmlFile) throws JAXBException, IOException {
JAXBContext jaxbContext = JAXBContext.newInstance(objClass);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
return objClass.cast(unmarshaller.unmarshal(xmlFile));
}
}