Java XML JAXB Object to XML objectToXML(Class cls, Object entity)

Here you can find the source of objectToXML(Class cls, Object entity)

Description

Return the xml translation of an object

License

Open Source License

Parameter

Parameter Description
cls a parameter
entity a parameter

Declaration

public static String objectToXML(Class<?> cls, Object entity) 

Method Source Code

//package com.java2s;
/*/*w w  w.  j a va  2  s .co  m*/
 * Author Stephen Booysen
 *
 * Copyright (c) 2015 Stephen Booysen, Inc. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * Stephen Booysen. ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Stephen Booysen
 *
 * Stephen Booysen MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

import java.io.StringWriter;

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

public class Main {
    /**
     * Return the xml translation of an object
     * 
     * @param cls
     * @param entity
     * @return
     */
    public static String objectToXML(Class<?> cls, Object entity) {

        try {
            Marshaller m = JAXBContext.newInstance(cls).createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
            StringWriter sw = new StringWriter();
            m.marshal(entity, sw);
            return sw.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. getObjects(List objEls)
  2. getXmlString(JAXBElement versioningInfo, Boolean formatXml, Schema schema)
  3. getXMLString(Object person, Class clazz)
  4. getXmlString(T jaxbObject)
  5. Object2Xml(Object object)
  6. ObjectToXml(Object object)
  7. objectToXml(Object source, Class... type)
  8. toString(E e)
  9. toString(Object o, Class clazz)