xml和对象的转换

xml和对象的转换,第1张

xml和对象的转换 工具类
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import cn.hutool.core.util.XmlUtil;
import com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler;

class XmlUtils extends XmlUtil {

    /**
     * xml字符串转为bean
     * @param xml xml字符串
     * @param clazz 需要转成的对象
     * @return
     */
    @SuppressWarnings("unchecked")
    public static  T parseBean(String xml, Class clazz) {
        /*try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }*/
        StringReader reader = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(xml);
            @SuppressWarnings("unchecked")
            T t = (T) unmarshaller.unmarshal(reader);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return null;
    }
    /**
     * 将对象转为xml字符串
     * 编码为utf-8
     * 不格式化
     * 省略头部声明
     * @param obj 待转的对象
     * @return
     */
    public static String toStr(Object obj) {
        return toStr(obj, false, true);
    }
    /**
     * 将对象转为xml字符串
     * 编码为utf-8
     * @param obj 待转的对象
     * @param isFormat 是否格式化
     * @param isIgnoreHead 是否忽略头部
     * @return
     */
    public static String toStr(Object obj, boolean isFormat, boolean isIgnoreHead) {
        StringWriter writer = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, isFormat);// 是否格式化生成的xml串
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, isIgnoreHead);// 是否省略xm头声明信息

            // 不进行转义字符的处理
            marshaller.setProperty(CharacterEscapeHandler.class.getName(),
                    new CharacterEscapeHandler() {
                        @Override
                        public void escape(char[] ch, int start, int length,
                                           boolean isAttVal, Writer writer) throws IOException {
                            writer.write(ch, start, length);
                        }
                    });

            writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 将对象转为xml字符串
     * 编码为utf-8
     * 格式化
     * 省略头部声明
     * @param obj 待转的对象
     * @return
     */
    public static String toPrettyStr(Object obj) {
        return toStr(obj, true, true);
    }


    /**
     * 将对象转为xml字符串
     * 编码为 GBK
     * @param obj 待转的对象
     * @param isFormat 是否格式化
     * @param isIgnoreHead 是否忽略头部
     * @return
     */
    public static String toStrGF(Object obj, boolean isFormat, boolean isIgnoreHead) {
        StringWriter writer = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");// //编码格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, isFormat);// 是否格式化生成的xml串
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, isIgnoreHead);// 是否省略xm头声明信息
            // 不进行转义字符的处理
            marshaller.setProperty(CharacterEscapeHandler.class.getName(),
                    new CharacterEscapeHandler() {
                        @Override
                        public void escape(char[] ch, int start, int length,
                                           boolean isAttVal, Writer writer) throws IOException {
                            writer.write(ch, start, length);
                        }
                    });

            writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 对象转为xml文件
     *
     * @param obj
     * @param beanClass 对象的class
     * @return
     */
    public static String beanToXml(Object obj, Class beanClass) {
        StringWriter writer = null;
        try {
            JAXBContext context = JAXBContext.newInstance(beanClass);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();

        } catch (JAXBException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
bean对象
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.xml.bind.annotation.XmlRootElement;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@XmlRootElement(name="root")
public class TestRootVo {
    private TestHeadVo head;
    private TestBodyVo body;
}

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import javax.xml.bind.annotation.XmlRootElement;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@XmlRootElement(name="head")
public class TestHeadVo  {
    private String TRAN_TIME;
    private String SERVICE_CODE;
    private String SEQ_NO;
}

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import javax.xml.bind.annotation.XmlRootElement;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@XmlRootElement(name="body")
public class TestBodyVo {
    private String QUEUE_NO;
    private String COUNTER_NO;
    private String IS_RECALL;
    private String COUNTER_TYPE;
}
测试
@org.junit.Test
    public void test5(){
        String xmlStr = "\n" +
                "\t\n" +
                "\t\t\n" +
                "\t\t\t***\n" +
                "\t\t\t1234567890000000000\n" +
                "\t\t\t2017012012111111\n" +
                "\t\t\n" +
                "\t\t\n" +
                "\t\t\tCN0010321\n" +
                "\t\t\t1\n" +
                "\t\t\t1\n" +
                "\t\t\t1\n" +
                "\t\t\n" +
                "\t";
        TestRootVo testRootVo = XmlUtils.parseBean(xmlStr, TestRootVo.class);
        System.out.println(testRootVo);
        System.out.println(testRootVo.getBody());
        System.out.println(testRootVo.getHead());
        System.out.println(XmlUtils.toStr(testRootVo,true,false));
        System.out.println(XmlUtils.toStrGF(testRootVo,true,false));
    }
测试输出
TestRootVo(head=TestHeadVo(TRAN_TIME=20170120121332, SERVICE_CODE=T0501, SEQ_NO=1234567890000000000), body=TestBodyVo(QUEUE_NO=CN0010321, COUNTER_NO=1, IS_RECALL=1, COUNTER_TYPE=1))
TestBodyVo(QUEUE_NO=CN0010321, COUNTER_NO=1, IS_RECALL=1, COUNTER_TYPE=1)
TestHeadVo(TRAN_TIME=20170120121332, SERVICE_CODE=T0501, SEQ_NO=1234567890000000000)


    
        1
        1
        1
        CN0010321
    
    
        1234567890000000000
        T0501
        20170120121332
    




    
        1
        1
        1
        CN0010321
    
    
        1234567890000000000
        T0501
        20170120121332
    

原文: https://blog.csdn.net/weixin_40691089/article/details/106529266

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/992478.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存