Java XML JAXB Object to XML convertToXml(Object obj)

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

Description

convert To Xml

License

Open Source License

Declaration

public static String convertToXml(Object obj) 

Method Source Code


//package com.java2s;
import java.io.File;

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

public class Main {

    public static String convertToXml(Object obj) {
        return convertToXml(obj, "UTF-8");
    }/*w  ww  .j a  v  a2s.c  o m*/

    public static String convertToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static boolean convertToXml(Object obj, String encoding, File file) {
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

            marshaller.marshal(obj, file);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

Related

  1. asXml(T object)
  2. convertObjectToXml(Object object)
  3. convertObjectToXML(Object object)
  4. convertToString(Object obj)
  5. convertToXml(Object obj)
  6. convertToXml(Object obj, String encoding)
  7. createXML(Object o)
  8. getObjects(List> objEls)