Java工具【十六】XmlUtil:dom4j格式化写入xml

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.mybatis.generator.api.GeneratedXmlFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

public class XmlUtil {

	public static void writeDocument2Xml(Document document, String xmlFileName) throws IOException {
		// 创建字符串缓冲区
		// StringWriter stringWriter = new StringWriter();
		// 设置文件编码
		OutputFormat xmlFormat = new OutputFormat();
		xmlFormat.setEncoding("UTF-8");
		// 设置换行
		xmlFormat.setNewlines(true);
		// 生成缩进
		xmlFormat.setIndent(true);
		// 使用4个空格进行缩进, 可以兼容文本编辑器
		xmlFormat.setIndent("    ");

		// 创建写文件方法
		// XMLWriter xmlWriter = new XMLWriter(fileWriter,xmlFormat);
		FileOutputStream output = null;
		XMLWriter writer = null;

		try {
			File file = new File(xmlFileName);
			System.out.println(file.getParentFile().getAbsolutePath());
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			output = new FileOutputStream(file);
			writer = new XMLWriter(output, xmlFormat);
			writer.write(document);
			writer.flush();
		} finally {
			IOUtils.closeQuietly(output);
			if (writer != null) {
				writer.close();
			}
		}
	}

	public static String writeElement2String(Element element) throws IOException {
		StringWriter stringWriter = new StringWriter();
		writeFormat(element, stringWriter);
		return stringWriter.toString();
	}

	public static String writeDocument2String(Document document) throws IOException {
		StringWriter stringWriter = new StringWriter();
		writeFormat(document, stringWriter);
		return stringWriter.toString();
	}

	private static void writeFormat(Node node, StringWriter stringWriter) throws IOException {
		// 设置文件编码
		OutputFormat xmlFormat = new OutputFormat();
		xmlFormat.setEncoding("UTF-8");
		// 设置换行
		xmlFormat.setNewlines(true);
		// 生成缩进
		xmlFormat.setIndent(true);
		// 使用4个空格进行缩进, 可以兼容文本编辑器
		xmlFormat.setIndent("    ");

		// 创建写文件方法
		XMLWriter writer = null;

		try {
			// 创建字符串缓冲区
			writer = new XMLWriter(stringWriter, xmlFormat);
			writer.write(node);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}


}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值