Convert Object to XML using JAXB - Android XML

Android examples for XML:JAXB

Description

Convert Object to XML using JAXB

Demo Code


//package com.java2s;
import javax.xml.bind.JAXBContext;

import javax.xml.bind.Marshaller;

import java.io.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object object = "java2s.com";
        System.out.println(toXml(object));
    }/*from   w ww  . ja  v a  2s . c  o  m*/

    private static final String ENCODING = "GBK";

    public static boolean toXml(Object object, File xml) {
        if (object == null) {
            throw new NullPointerException("object??????!");
        }
        JAXBContext jc = null;
        Marshaller m = null;
        try {
            jc = JAXBContext.newInstance(object.getClass());
            m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            m.setProperty(Marshaller.JAXB_ENCODING, ENCODING);
            m.marshal(object, xml);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String toXml(Object object) {
        if (object == null) {
            throw new NullPointerException("object??????!");
        }
        JAXBContext jc = null;
        Marshaller m = null;
        String xml = null;
        try {
            jc = JAXBContext.newInstance(object.getClass());
            m = jc.createMarshaller();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            m.marshal(object, bos);
            xml = new String(bos.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return xml;
    }
}

Related Tutorials