zoukankan      html  css  js  c++  java
  • xstream实现xml字符串与对象直接的转换

    /**
     * TODO 使用xStream 实现xml字符和对象之间的转换
     * <p>
     * <!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
     * <!-- xml字符串,对象之间互转 -->
     * <dependency>
     * <groupId>com.thoughtworks.xstream</groupId>
     * <artifactId>xstream</artifactId>
     * <version>${xstream.version}</version>
     * </dependency>
     *
     * @author: geekswg@qq.com
     * @since: 2020/8/1 10:31
     */
    public class XmlUtils {
    
        private static final XStream xStreamHelper = new XStream(new StaxDriver());
        // 初始化配置
        static {
            XStream.setupDefaultSecurity(xStreamHelper);
            xStreamHelper.allowTypesByWildcard(new String[]{"org.demo.springcloud.**"});
            xStreamHelper.ignoreUnknownElements();//忽略未知节点
            xStreamHelper.autodetectAnnotations(true);
        }
    
        public static <T> T xmlToBean(String xmlStr, Class<?> clazz) {
            xStreamHelper.ignoreUnknownElements();//忽略未知节点
            xStreamHelper.autodetectAnnotations(true);
            xStreamHelper.processAnnotations(clazz);
            return (T) xStreamHelper.fromXML(xmlStr);
        }
    
        public static <T> T xmlToBean(File xmlFile, Class<?> clazz) {
            xStreamHelper.processAnnotations(clazz);
            return (T) xStreamHelper.fromXML(xmlFile);
        }
    
        public static <T> String beanToXmlStr(T t) {
            return xStreamHelper.toXML(t);
        }
    
        public static <T> boolean beanToXml(T t, String filePath){
            boolean flag = true;
            try {
                FileWriter fileWriter = new FileWriter(new File(filePath));
                fileWriter.write(xStreamHelper.toXML(t));
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e) {
                flag = false;
                e.printStackTrace();
            }finally {
                return flag;
            }
        }
    
        public static void main(String[] args) {
            BsBankInfo bsBankInfo = new BsBankInfo();
            bsBankInfo.setBankName("中国建设银行");
            bsBankInfo.setBankNo("b10001");
    
            String xmlStr = beanToXmlStr(bsBankInfo);
            System.out.println("===>" + xmlStr);
            System.out.println(xmlToBean(xmlStr, BsBankInfo.class).toString());
            System.out.println(beanToXml(bsBankInfo, "d:/t.xml"));
        }
    }
  • 相关阅读:
    给Array本地对象增加一个原型方法,它用于删除数组条目中重复的条目(可能有多个),返回值是一个包含被删除的重复条目的新数组以及删除了重复条目的原数组。
    mysql批量替换某个字段的值!
    LInux常用命令
    盒模型布局
    box-sizing -- 盒模型
    vue中使用svg字体图标
    字体图标
    在线字体
    Java QQ邮箱发送邮件
    Java 对全局用户是否登录验证
  • 原文地址:https://www.cnblogs.com/geekswg/p/13413848.html
Copyright © 2011-2022 走看看