美文网首页
JAXBContext简单实例,对象转xml和xml转对象

JAXBContext简单实例,对象转xml和xml转对象

作者: xywh | 来源:发表于2020-02-29 18:28 被阅读0次

对象转xml

 /**
     * 将指定对象转换为xml字符串
     *
     * @param object
     * @return
     * @throws JAXBException 
     */
    public static String objectToXmlStr(Object object) throws JAXBException {
        String xmlObj = "";
        //1、调用JAXBContext,获取上下文对象
        JAXBContext context = JAXBContext.newInstance(object.getClass());
        //2、根据上下文获取marshaller对象
        Marshaller m = context.createMarshaller();
        //3、设置编码字符集,一般设置UTF-8
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        //4、格式化XML输出,有分行和缩进
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        //5、调用Marshaller类的marshal方法,编排内容到输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        m.marshal(object, baos);
        //6、将输出流生成XML字符串
        xmlObj = new String(baos.toByteArray());
        return xmlObj.trim();
    }

xml转对象

  /**
     * 将String类型的xml转换成对象
     *
     * @param clazz
     * @param xmlStr
     * @return
     */
    public static Object xmlStrToObject(Class clazz, String xmlStr) {
        Object xmlObject = null;
        try {
            xmlObject= clazz.newInstance();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            //1、调用JAXBContext,获取上下文对象
            JAXBContext context = JAXBContext.newInstance(clazz.getClass());
            //2、调用JAXBContext类的createUnmarshaller方法,创建反编排器
            Unmarshaller u = context.createUnmarshaller();
            //3、将xml字符串进行反编排
            xmlObject = u.unmarshal(new StringReader(xmlStr));
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return xmlObject;
    }

相关文章

网友评论

      本文标题:JAXBContext简单实例,对象转xml和xml转对象

      本文链接:https://www.haomeiwen.com/subject/xejmhhtx.html