package cn.jbolt.writefile;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class CreateXML {
private static final String xmlPath = "F:\\demo.xml";
public static void main(String[] args) {
createXml(xmlPath);
}
/**
* 生成xml方法
*/
public static void createXml(String xmlPath) {
try {
// 创建解析器工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder domBuilder = factory.newDocumentBuilder();
Document document = domBuilder.newDocument();
// 不显示standalone="no"
document.setXmlStandalone(true);
Element bookstore = document.createElement("folder");
String [] demo = new String[2];
List<String> dataList = Arrays.asList(demo);
dataList.forEach(action ->{
Element file = document.createElement("file");
Element num = document.createElement("num");
num.setTextContent("1");
//其他方法请自行 . 出来
Element no = document.createElement("no");
no.setTextContent("档号");
Element responsible = document.createElement("responsible");
Element title = document.createElement("title");
Element date = document.createElement("date");
Element classification = document.createElement("classification");
Element electronicName = document.createElement("electronicName");
Element note = document.createElement("note");
file.appendChild(num);
file.appendChild(no);
file.appendChild(responsible);
file.appendChild(title);
file.appendChild(date);
file.appendChild(classification);
file.appendChild(electronicName);
file.appendChild(note);
bookstore.appendChild(file);
});
document.appendChild(bookstore);
// 创建TransformerFactory对象
TransformerFactory tff = TransformerFactory.newInstance();
// 创建 Transformer对象
Transformer tf = tff.newTransformer();
// 输出内容是否使用换行
tf.setOutputProperty(OutputKeys.INDENT, "yes");
// 创建xml文件并写入内容
tf.transform(new DOMSource(document), new StreamResult(new File(xmlPath)));
System.out.println("生成demo.xml成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("生成demo.xml失败");
}
}
}