采用DOM方式生成xml文件

package com.zhang.xml.dom;

import java.io.File;

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 DomCreate {

	public static void main(String[] args) throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbf.newDocumentBuilder();

		Document document = dBuilder.newDocument();
		document.setXmlStandalone(true);
		Element booksEle = document.createElement("books");
		
		Element bookEle = document.createElement("book");
		bookEle.setAttribute("id", "book1");
		
		Element nameEle = document.createElement("name");
		nameEle.setTextContent("bookName1");
		
		document.appendChild(booksEle);
		booksEle.appendChild(bookEle);
		bookEle.appendChild(nameEle);
		
		TransformerFactory tff = TransformerFactory.newInstance();
		Transformer tf = tff.newTransformer();
		tf.setOutputProperty(OutputKeys.INDENT, "yes");//换行
		tf.transform(new DOMSource(document),new StreamResult(new File("dom_books.xml")));
	}
}


你可能感兴趣的:(java,dom,生成XML)