Java实现将数据生成xml信息文件

前言

XML作为轻量级的数据存储文件,主要拥有以下优点:

  • 数据内容和机构完全分离。方便作为源数据的后续操作。
  • 互操作性强。大多数纯文本的文件格式都具有这个优点。纯文本文件可以方便地穿越防火墙,在不同操作系统上的不同系统之间通信。
  • 规范统一。XML具有统一的标准语法,任何系统和产品所支持的XML文档,都具有统一的格式和语法。
  • 支持多种编码。方便了多语言系统对xml数据的处理。
  • 可扩展性。XML是一种可扩展的语言,可以根据XML的基本语法来进一步限定使用范围和文档格式,从而定义一种新的语言。
    由以上优点可以得出xml在开发过程中的用途非常广泛的结论。我需要把数据转为xml文件,也是因为其操作相对比较遍历。

实现

引入jar包

    <!-- xml文件生成 -->
    <dependency>
	<groupId>org.jdom</groupId>
	<artifactId>jdom</artifactId>
	<version>1.1</version>
    </dependency>

实现代码

    /**
     * @Description 通过数据创建Xml文件
     * @param rootName
     * @param channelName
     * @param fileName
     * @param mapItems
     * @Return void
     * @Author Mr.Walloce
     * @Date 2019/9/5 11:59
     */
   private void createXml(String rootName, String channelName, String fileName, List<Map<String, String>> mapItems) {
	   if (mapItems == null) {
		   return;
	   }
	   try {
           // 生成一个根节点
           Element root = new Element(rootName);

           // 生成一个document对象
           Document document = new Document(root);

           //添加子节点数据
           this.buildNodes(root, channelName, mapItems);

           Format format = Format.getCompactFormat();
           // 设置换行Tab或空格
           format.setIndent("	");
           format.setEncoding("UTF-8");

           // 创建XMLOutputter的对象
           XMLOutputter outputer = new XMLOutputter(format);
           // 利用outputer将document转换成xml文档
           File file = new File(fileName+".xml");
           if (!file.exists()) {
        	   file.getParentFile().mkdirs();
           }
           file.createNewFile();
           outputer.output(document, new FileOutputStream(file));
       } catch (Exception e) {
           e.printStackTrace();
           log.error("生成xml失败");
       }
   }

   /**
     * @Description 构建子节点数据
     * @param root
     * @param channelName
     * @param mapItems
     * @Return void
     * @Author Mr.Walloce
     * @Date 2019/9/5 11:56
     */
   private void buildNodes(Element root, String channelName, List<Map<String, String>> mapItems) {
       Element channel = null;
       Element node = null;
       for (Map<String, String> mapItem : mapItems) {
           channel = new Element(channelName);
           for (Map.Entry<String, String> entry : mapItem.entrySet()) {
               node = new Element(entry.getKey());
               node.setText(entry.getValue());
               channel.addContent(node);
           }
           root.addContent(channel);
       }
   }

以上参数mapItems为要生成xml文件的数据集,key为xml文件的节点属性,value则为节点属性的值。

初心回归,时光已逝!
原文地址:https://www.cnblogs.com/yin1361866686/p/11642120.html