DOM生成XML文件

将生成的XML文件保存到硬盘上,需要使用的类有TransformerFactory,Transformer,DOMSource,StreamResult。


import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
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;

/**
 * 将生成的xml文件输出到文件中
 * @author ad
 *
 */
public class DOMOutDemo {
	public static void main(String[] args) {
		//①建立DocumentBuilderFactory,用于取得DocumentBuilder
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		
		//②通过DocumentBuilderFactory来取得DocumentBuilder
		DocumentBuilder builder = null;
		try {
			builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		
		//③定义Document接口对象,通过DocumentBuilder类进行DOM树的转换操作
		Document doc = null;
		doc = builder.newDocument();//创建一个新的文档
		
		//④建立各个操作节点
		Element addresslist = doc.createElement("addresslist");//建立节点
		Element linkman = doc.createElement("linkman");
		Element name = doc.createElement("name");
		Element email = doc.createElement("email");
		
		//⑤设置节点的文本内容,即为每一个节点添加文本节点
		name.appendChild(doc.createTextNode("用户"));//设置文本
		email.appendChild(doc.createTextNode("[email protected]"));
		
		//⑥设置节点关系
		linkman.appendChild(name);
		linkman.appendChild(email);
		addresslist.appendChild(linkman);//子节点
		doc.appendChild(addresslist);//文档上保持节点
		
		//⑦输出文档到文件中
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer t = null;
		try {
			t = tf.newTransformer();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		}
		t.setOutputProperty(OutputKeys.ENCODING, "GB2312");//设置编码
		DOMSource source = new DOMSource(doc);//输出文档
		StreamResult result = new StreamResult(new File("D:"+File.separator+"testXML\\output.xml"));//指定输出位置
		try {
			t.transform(source, result);
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		
	}

}



这行代码我改成GBK或者UTF-8就不能正常显示中文了 求教
t.setOutputProperty(OutputKeys.ENCODING, "GB2312");//设置编码

你可能感兴趣的:(xml)