zoukankan      html  css  js  c++  java
  • 读写XML(1)关于Dom4j 生成xml文件,以及格式化的xml文件的样例

       项目中遇到了读写xml文件的问题,下面贴上代码再逐一解释
     1private void saveToXmlFile(ProcessInfo[] infos)
     2        {
     3            if (dom == null)
     4            {
     5                loadProcessInfo(true);
     6            }

     7            XMLWriter writer = null;
     8            try
     9            {
    10                OutputFormat format = OutputFormat.createPrettyPrint();
    11                writer = new XMLWriter(new FileWriter(filepath), format);
    12                if (dom != null)
    13                {
    14                    dom.clearContent();
    15                }

    16                dom = DocumentHelper.createDocument();
    17                dom.setXMLEncoding("utf-8");
    18                
    19                Element root = dom.addElement("processes");
    20                for (int i = 0; i < infos.length; i++)
    21                {
    22                    info2Element(root, infos[i]);
    23                }

    24                
    25                writer.write(dom);
    26                writer.flush();
    27            }

    28            catch (IOException e)
    29            {
    30                log.error("存储XML文件出错", e);
    31            }

    32            finally
    33            {
    34                if (writer != null)
    35                {
    36                    try
    37                    {
    38                        writer.close();
    39                    }

    40                    catch (IOException e)
    41                    {
    42                        // TODO Auto-generated catch block
    43                        e.printStackTrace();
    44                    }

    45                }

    46            }

    47            
    48            
    49        }
    创建xml 的主要类 DocumentHelper
    见Line:16
    dom = DocumentHelper.createDocument();
    dom.setXMLEncoding("utf-8");
    创建Document对象并设置编码
    写入文件的主要类XMLWriter
    格式化xml的辅助类OutputFormat
    其创建过程参见Line 10
    OutputFormat format = OutputFormat.createPrettyPrint();
    writer = new XMLWriter(new FileWriter(filepath), format);
    然后Document创建根Element
    info2Element()的方法则是将对象转换到Element结构中去。
    格式化的主要功臣就是 OutputFormat  相应的还有createCompactFormat() 创建压缩的xml文件,删去了所有的换行等无用的字符。createPrettyPrint() 则是生成格式化的xml 代码,让看起来好读一点。




  • 相关阅读:
    async/await语法
    generator生成器函数
    数组练习
    解决异步(重点promise函数)
    iterator遍历器
    各种遍历方法(重点for....of)
    ES6代理proxy
    Symbol新数据类型
    函数(rest 箭头)
    ES6常用方法(字符串,数字,数组,对象)
  • 原文地址:https://www.cnblogs.com/philips/p/1247506.html
Copyright © 2011-2022 走看看