可把xml格式化

   ① 创建OutputStreamWriter对象,构造方法中传递字节输出流和指定的编码表名称

    ② 使用OutputStreamWriter对象中的方法write,把字符转换为字节存储缓冲区中(编码)

    ③ 使用OutputStreamWriter对象中的方法flush,把内存缓冲区中的字节刷新到文件中(使用字节流写字节的过程)

    ④ 释放资源

package me.gorden.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;

public class XmlTest {

    public static void main(String[] args) {

         String path ="D:/Users.xml";
        SAXReader reader = new SAXReader();
        try {
            Document doc = reader.read(path);

            OutputFormat format = new OutputFormat("\t",true);
            format.setTrimText(true);

            OutputStreamWriter  osw = new OutputStreamWriter(new FileOutputStream(path),"UTF-8");
            XMLWriter writer = new XMLWriter(osw,format);
            writer.write(doc);
            writer.close();
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/yemenlinweihan/article/details/107650752