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();
}
}
}
}