Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;

import javax.xml.bind.Marshaller;

public class Main {
    public static String bean2Xml(Object bean) {
        String xmlString = null;
        JAXBContext context;
        StringWriter writer;
        if (null == bean)
            return xmlString;
        try {
            context = JAXBContext.newInstance(bean.getClass());
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);//
            //m.setProperty(Marshaller.JAXB_ENCODING, "gb2312");//
            //m.setProperty(Marshaller.JAXB_ENCODING, "GBK");//
            m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");//
            m.setProperty(Marshaller.JAXB_FRAGMENT, false);//
            writer = new StringWriter();
            m.marshal(bean, writer);
            xmlString = writer.toString();
            return xmlString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlString;
    }

    public static String bean2Xml(Object bean, String codetype) {
        String xmlString = null;
        JAXBContext context;
        StringWriter writer;
        if (null == bean)
            return xmlString;
        try {
            context = JAXBContext.newInstance(bean.getClass());
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);//
            // m.setProperty(Marshaller.JAXB_ENCODING, "gb2312");//
            // m.setProperty(Marshaller.JAXB_ENCODING, "GBK");//
            m.setProperty(Marshaller.JAXB_ENCODING, codetype);//
            m.setProperty(Marshaller.JAXB_FRAGMENT, false);//
            writer = new StringWriter();
            m.marshal(bean, writer);
            xmlString = writer.toString();
            return xmlString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlString;
    }
}