Java XML JAXB Object to XML toXml(final T dto)

Here you can find the source of toXml(final T dto)

Description

to Xml

License

Apache License

Declaration

public static <T> String toXml(final T dto) 

Method Source Code

//package com.java2s;
/**//from  ww  w. j a va  2s  . c om
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You 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.CharArrayWriter;

import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main {
    public static <T> String toXml(final T dto) {
        final CharArrayWriter caw = new CharArrayWriter();
        toXml(dto, caw);
        return caw.toString();
    }

    public static <T> void toXml(final T dto, final Writer writer) {
        Marshaller m = null;
        try {
            final Class<?> aClass = dto.getClass();
            m = getJaxbContext(aClass).createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(dto, writer);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    private static JAXBContext getJaxbContext(Class<?> dtoClass) {
        try {
            return JAXBContext.newInstance(dtoClass);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. objectToXml(Object source, Class... type)
  2. toString(E e)
  3. toString(Object o, Class clazz)
  4. toXml(Class className, Object object)
  5. toXML(final Object obj, final boolean prettyPrint)
  6. toXML(Object o)
  7. toXML(Object o, OutputStream os)
  8. toXml(Object o, OutputStream output)
  9. toXml(Object obj)