Java Utililty Methods XML JAXB Serialize

List of utility methods to do XML JAXB Serialize

Description

The list of methods to do XML JAXB Serialize are organized into topic(s).

Method

voidserializeToFile(Class clazz, T object, String outputFile)
serialize To File
JAXBContext context = JAXBContext.newInstance(clazz);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(object, new FileOutputStream(outputFile));
voidserializeToSTD(Object obj)
serialize To STD
final Marshaller m = JAXBContext.newInstance(obj.getClass()).createMarshaller();
m.setProperty(JAXB_FRAGMENT, TRUE);
m.marshal(obj, out);
StringserializeToString(Object obj)
serialize To String
if (obj == null || !obj.getClass().isAnnotationPresent(XmlRootElement.class))
    return null;
try (StringWriter writer = new StringWriter()) {
    try {
        JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
        ctx.createMarshaller().marshal(obj, writer);
        return writer.toString();
    } catch (JAXBException ex) {
...
StringserializeToString(Object obj)
serialize To String
java.io.StringWriter sw = new StringWriter();
final Marshaller m = JAXBContext.newInstance(obj.getClass()).createMarshaller();
m.setProperty(JAXB_FRAGMENT, TRUE);
m.setProperty(JAXB_FORMATTED_OUTPUT, TRUE);
m.marshal(obj, sw);
return sw.toString();
voidserializeToXmlFile(T object, String fileName)
serialize To Xml File
try {
    JAXBContext context = JAXBContext.newInstance(object.getClass());
    try (FileOutputStream outStream = new FileOutputStream(fileName)) {
        context.createMarshaller().marshal(object, outStream);
} catch (JAXBException | IOException e) {
voidxmlSerialize(String filename, T obj)
Serialize an object to file as XML.
FileOutputStream fileOut = new FileOutputStream(filename);
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(obj, fileOut);