首页 > 编程语言 > 详细

Java根据Bean对象导出XML文件

时间:2021-08-14 16:52:11      阅读:17      评论:0      收藏:0      [点我收藏+]

Java导出Xml文件

工具类

package com.ruoyi.common.h1wUtils.xml;
?
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import lombok.Data;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
?
import java.io.File;
import java.util.ArrayList;
import java.util.List;
?
/**
* @Author lian-chen
* @Date 2021/7/19 14:01
*/
public class XmlUtils {
   private static final Logger log = LoggerFactory.getLogger(XmlUtils.class);
   /**解决解析下划线时出现双下划线*/
   public static final XStream XSTREAM = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
?
   /**
    * 将obj转换成xml的字符串
    *
    * @param obj
    * @return str
    */
   public static String beanToXmlStr(Object obj) {
       XSTREAM.processAnnotations(obj.getClass());
       String xml = XSTREAM.toXML(obj);
       return xml;
  }
?
   /**
    * 将xml类型的字符串转换成cls类型的对象
    *
    * @param xmlStr
    * @param cls
    * @return cls类型的对象
    */
   public static <T> T xmlStrToBean(String xmlStr, Class<T> cls) {
       try {
           XStream xstream = new XStream(new DomDriver());
           xstream.processAnnotations(cls);
           @SuppressWarnings("unchecked")
           T obj = (T) xstream.fromXML(xmlStr);
           return obj;
      } catch (Exception e) {
           e.printStackTrace();
           return null;
      }
  }
?
   /**
    * bean转换成对应路径下的xml文件
    *
    * @param file 对应路径的xml地址
    * @param obj 需要转换的对象
    * @return true 转换成功 ;false 转换失败
    * @throws IOException
    */
   public static boolean beanToXmlFile(String filePath, Object obj) {
       try {
           File file = new File(filePath);
           if (!file.getParentFile().exists()) {
               file.getParentFile().mkdirs();
          }
           if (!file.exists()) {
               file.createNewFile();
          }
           XSTREAM.processAnnotations(obj.getClass());
           String xml = XSTREAM.toXML(obj);
           FileUtils.write(file, xml, "utf-8");
           log.info("Xml Create Success:" + file.getAbsolutePath());
           return true;
      } catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
           log.error("xml Io生成异常", e);
           return false;
      }
  }
?
   /**
    * 路径file对应的xml文件转换成obj
    *
    * @param file
    * @param cls
    * @return
    * @throws IOException
    */
   public static <T> T xmlToBeanFile(String filePath, Class<T> cls) {
       File file = new File(filePath);
       try {
           if (!file.exists()) {
               return null;
          }
           XSTREAM.processAnnotations(cls);
           @SuppressWarnings("unchecked")
           T t = (T) XSTREAM.fromXML(FileUtils.readFileToString(file, "UTF-8"));
           return t;
      } catch (Exception e) {
           e.printStackTrace();
           log.error("io 获取异常,没有" + filePath + "文件", e);
           return null;
      }
  }
?
?
   /**
    * 使用
    */
   @Data
   /**
    * 基类别名
    */
   @XStreamAlias("User")
   static class User{
       /**
        * 属性别名
        */
       @XStreamAlias("Username")
       private String username;
       @XStreamAlias("Age")
       private Integer age;
       /**
        * 子集别名
        */
       @XStreamImplicit(itemFieldName = "PetList")
       private List<Pet> petList;
  }
?
   @Data
   /**
    * 定义了子集别名 是有基类定义的别名
    */
   @XStreamAlias("Pet")
   static class Pet{
       @XStreamAlias("Name")
       private String name;
       @XStreamAlias("Color")
       private String color;
  }
?
   public static void main(String[] args) {
           User user = new User();
           user.setUsername("zhangsan");
           user.setAge(18);
           List<Pet> pets = new ArrayList<>(2);
           for (int j = 0; j < 2; j++) {
               Pet pet = new Pet();
               pet.setName("pet"+j);
               pet.setColor("black"+j);
               pets.add(pet);
          }
           user.setPetList(pets);
       String filePath = "d:/"+ DateUtils.datePath() + File.separator + UUID.fastUUID().toString()+".xml";
       boolean b = XmlUtils.beanToXmlFile(filePath, user);
       if (b) {
//           转换成功
      }
  }
}
?

pom

        <dependency>
           <groupId>com.thoughtworks.xstream</groupId>
           <artifactId>xstream</artifactId>
           <version>1.4.10</version>
       </dependency>

格式

<User>
 <Username>zhangsan</Username>
 <Age>18</Age>
 <PetList>
   <Name>pet0</Name>
   <Color>black0</Color>
 </PetList>
 <PetList>
   <Name>pet1</Name>
   <Color>black1</Color>
 </PetList>
</User>

 

Java根据Bean对象导出XML文件

原文:https://www.cnblogs.com/liang-chen-fly/p/15141003.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!