//DOM写入
public static void createXMLByDOM(File dest) {
// 创建DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
// 创建DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// 创建Document
Document document = builder.newDocument();
// 设置XML声明中standalone为yes,即没有dtd和schema作为该XML的说明文档,且不显示该属性
// document.setXmlStandalone(true);
// 创建根节点
Element bookstore = document.createElement("bookstore");
// 创建子节点,并设置属性
Element book = document.createElement("book");
book.setAttribute("id", "1");
// 为book添加子节点
Element name = document.createElement("name");
name.setTextContent("安徒生童话");
book.appendChild(name);
Element author = document.createElement("author");
author.setTextContent("安徒生");
book.appendChild(author);
Element price = document.createElement("price");
price.setTextContent("49");
book.appendChild(price);
// 为根节点添加子节点
public static void createXMLByDOM(File dest) {
// 创建DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
// 创建DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// 创建Document
Document document = builder.newDocument();
// 设置XML声明中standalone为yes,即没有dtd和schema作为该XML的说明文档,且不显示该属性
// document.setXmlStandalone(true);
// 创建根节点
Element bookstore = document.createElement("bookstore");
// 创建子节点,并设置属性
Element book = document.createElement("book");
book.setAttribute("id", "1");
// 为book添加子节点
Element name = document.createElement("name");
name.setTextContent("安徒生童话");
book.appendChild(name);
Element author = document.createElement("author");
author.setTextContent("安徒生");
book.appendChild(author);
Element price = document.createElement("price");
price.setTextContent("49");
book.appendChild(price);
// 为根节点添加子节点