• 读写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 代码,让看起来好读一点。




  • 相关阅读:
    ServletContext笔记
    Session笔记
    Cookie笔记
    递归实现取数组最大值
    栈结构实现队列结构
    返回栈中最小元素的两种实现O(1)
    数组实现不超过固定大小的队列(环形数组)
    双向链表实现栈和队列
    Windows Server 2008 R2 / Windows Server 2012 R2 安装 .NET Core 3.1
    Windows 7 / Windows Server 2008 R2 升级至 SP1
  • 原文地址:https://www.cnblogs.com/philips/p/1247506.html
Copyright © 2020-2023  润新知