Java XML JAXB Object to XML toXMLString(Object obj)

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

Description

Convert an object with JAXB annotations to an XML string

License

Open Source License

Parameter

Parameter Description
cls a parameter
obj a parameter

Declaration

public static String toXMLString(Object obj) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2014 Open Door Logistics (www.opendoorlogistics.com)
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v3
 * which accompanies this distribution, and is available at http://www.gnu.org/licenses/lgpl.txt
 ******************************************************************************/

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

public class Main {
    /**//from w  ww . j av a  2s . c o m
     * Convert an object with JAXB annotations to an XML string
     * @param cls
     * @param obj
     * @return
     */
    public static String toXMLString(Object obj) {

        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            StringWriter writer = new StringWriter();
            m.marshal(obj, writer);
            return writer.toString();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. toXml(Object object)
  2. toXML(Object thing)
  3. toXml(T element)
  4. toXml(T object)
  5. toXMLString(final T binding)
  6. toXmlString(T obj, Class type)
  7. write(Object jaxbAnnotatedObj, OutputStream os)
  8. write(String filepath, T content, Class typeParameterClass)
  9. writeJaxbObject(OutputStream outputStream, JAXBElement jaxbElement, Class modelClass)