Java tutorial
//package com.java2s; /* * 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 java.util.ArrayList; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Main { /** * Return a list on obects converted to xml * * @param rootnode * @param cls * @param entities * @return */ public static String objectlistToXML(String rootnode, Class<?> cls, ArrayList<Object> entities) { StringBuilder builder = new StringBuilder(); if (rootnode != null) { builder.append("<" + rootnode + ">\n"); } for (Object entity : entities) { builder.append(objectToXML(cls, entity)); } if (rootnode != null) { builder.append("\n</" + rootnode + ">"); } return builder.toString(); } /** * 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; } }