Java XML JAXB Marshaller marshall(Object obj)

Here you can find the source of marshall(Object obj)

Description

marshall

License

Open Source License

Declaration

public static String marshall(Object obj) throws JAXBException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.io.FileWriter;
import java.io.IOException;

import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main {
    public static String marshall(Object obj) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());

        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        StringWriter w = new StringWriter();
        m.marshal(obj, w);//from w  ww  . j  a  v  a 2  s. com

        return w.toString();
    }

    public static File marshall(Object obj, File file) throws IOException, JAXBException {
        if (!file.exists() && !file.createNewFile())
            throw new IOException("Can't create " + file);
        if (!file.canWrite())
            throw new IOException("Can't write to " + file);
        JAXBContext context = JAXBContext.newInstance(obj.getClass());

        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        FileWriter w = new FileWriter(file);
        m.marshal(obj, w);
        w.close();

        return file;
    }
}

Related

  1. marshal(T t, Class entityClass)
  2. marshalAsString(Class clz, T marshalObj)
  3. marshall(Class c, String xml)
  4. marshall(final Object o, Class clazz)
  5. marshall(Object o)
  6. marshall(Object obj, URL schemaURL, Class... classesToBeBound)
  7. marshall(Object toMarshall)
  8. marshall(OutputStream os, JAXBElement element)
  9. marshall(String cntxtPkg, Object obj, OutputStream out)