Architect's xml----xml and object conversion tool class

1 Introduction.

As in question

2. code.

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
 
/**
 * XML helper class
 *
 * @author wanganqi
 * @version v1.0
 * @since Aug 13, 2014 at 2:38:52 PM
 */
public class XmlHelper
{
    /**
     * Convert custom data object to XML string
     *
     * @param clazz custom data type
     * @param object custom data object
     * @return XML string
     * @throws JAXBException exception
     */
    public static String objectToXML(Class clazz, Object object)
        throws JAXBException
    {
        String xml = null;
        JAXBContext context = JAXBContext.newInstance(clazz);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        Writer w = new StringWriter();
        m.marshal(object, w);
        xml = w.toString();
        return xml;
    }
 
    /**
     * Convert XML string to custom data object
     *
     * @param clazz custom data type
     * @param xml XML string
     * @return custom data object
     * @throws JAXBException exception
     */
    public static Object xmlToObject(Class clazz, String xml)
        throws JAXBException
    {
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller um = context.createUnmarshaller();
        return um.unmarshal(new StringReader(xml));
    }
}


Reprinted from: http://www.cnblogs.com/wgp13x/p/3995368.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326829636&siteId=291194637