Java XML JAXB Object to XML toString(E e)

Here you can find the source of toString(E e)

Description

to String

License

Apache License

Declaration

public static <E> String toString(E e) throws JAXBException 

Method Source Code

//package com.java2s;
/**/*from ww  w. ja v a  2 s  .  c om*/
 * Copyright 2015 Atos
 * Contact: Seaclouds
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

import java.io.ByteArrayOutputStream;

import java.io.OutputStream;

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

public class Main {
    public static <E> String toString(E e) throws JAXBException {
        String charsetName = "utf-8";
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        print(e, os, e.getClass());
        try {
            return os.toString(charsetName);
        } catch (UnsupportedEncodingException e1) {
            throw new IllegalArgumentException(charsetName + " is not supported");
        }
    }

    public static <E> void print(E e) throws JAXBException {
        print(e, e.getClass());
    }

    public static <E> void print(E e, Class<?>... classesToBeBound) throws JAXBException {
        print(e, System.out, classesToBeBound);
    }

    public static <E> void print(E e, OutputStream os, Class<?>... classesToBeBound) throws JAXBException {
        JAXBContext jaxbContext;
        Marshaller jaxbMarshaller;
        jaxbContext = JAXBContext.newInstance(classesToBeBound);
        jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        /*
         * http://stackoverflow.com/a/22756191
         */
        jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
        jaxbMarshaller.marshal(e, os);
    }
}

Related

  1. getXmlString(T jaxbObject)
  2. Object2Xml(Object object)
  3. objectToXML(Class cls, Object entity)
  4. ObjectToXml(Object object)
  5. objectToXml(Object source, Class... type)
  6. toString(Object o, Class clazz)
  7. toXml(Class className, Object object)
  8. toXML(final Object obj, final boolean prettyPrint)
  9. toXml(final T dto)