java生成xml

public static String fromObject(Object to,String simpleName) throws Exception {
        Class clazz = to.getClass();
        StringWriter sw = new StringWriter();
        try {
            JAXBContext jc = JAXBContext.newInstance(to.getClass());
            Marshaller marshaller = jc.createMarshaller();
            // 是否格式化XML
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);

            QName name = new QName(simpleName);
            if(clazz.getAnnotations().length>0){
                Annotation annotation=clazz.getAnnotations()[0];
                if(annotation instanceof XmlRootElement){
                    XmlRootElement rootElement= (XmlRootElement) annotation;
                    name=new QName(rootElement.name());
                }
            }
            JAXBElement element = new JAXBElement(name, clazz, to);
            marshaller.marshal(element, sw);
            return sw.toString();
        } catch (JAXBException e) {
            throw new Exception(e);
        }
    }

--java method
XMLSMemberList list=new XMLSMemberList(xmlMemberDTOs);
        String string = BeanToXmlConverUtil.fromObject(list,"Member List");
        response.setContentType("text/xml");
        String filename=String.format("M_interface_Member_%s", JodaUtils.now().toString("yyyyMMdd_HHmm").toUpperCase());
        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + ".xml\"");
        StreamUtils.copy(new ByteArrayInputStream(string.getBytes()),response.getOutputStream());

猜你喜欢

转载自849058520.iteye.com/blog/2204553
今日推荐