Java XML JAXB Object to XML Object2Xml(Object object)

Here you can find the source of Object2Xml(Object object)

Description

Object Xml

License

Open Source License

Declaration

public static String Object2Xml(Object object) throws JAXBException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.StringWriter;

import java.net.URL;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;

public class Main {
    public static String Object2Xml(Object object) throws JAXBException {
        Marshaller mar = createMarshallerByClazz(object.getClass());
        StringWriter strWriter = new StringWriter();
        mar.marshal(object, strWriter);//from  w w w  . j  a  v a2s .  co m
        return strWriter.toString();
    }

    public static String Object2Xml(Object object, URL schema_url) throws JAXBException, SAXException {
        Marshaller mar = createMarshallerByClazz(object.getClass());
        StringWriter strWriter = new StringWriter();
        if (schema_url != null) {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(schema_url);
            mar.setSchema(schema);
        }
        mar.marshal(object, strWriter);
        return strWriter.toString();
    }

    public static Marshaller createMarshallerByClazz(Class<?> clazz) throws JAXBException {
        JAXBContext jax = JAXBContext.newInstance(clazz);
        Marshaller mar = jax.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FRAGMENT, true);
        return mar;
    }
}

Related

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