XML文件写入之DOM解析操作

前端之家收集整理的这篇文章主要介绍了XML文件写入之DOM解析操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

DOM写入XML文件步骤如下:

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;




public class XMLWriterTest {

	public static void main(String[] args) {
//1.建立DocumentBuilderFactory
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//2.建立DocumentBuilder
		DocumentBuilder builder=  null;
		try {
			builder= factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//3.建立Document接口对象
		Document  doc = null;
		doc=builder.newDocument();
//4.建立各个操作节点
		Element addresslist = doc.createElement("addresslist");
		Element linkman = doc.createElement("linkman");
		Element name = doc.createElement("name");
		Element tel = doc.createElement("tel");
//5.设置节点的文本内容,即为每一个节点创建已给文本节点
		name.appendChild(doc.createTextNode("张大大"));//如果是存在多个name,这个问题如何解决???
		tel.appendChild(doc.createTextNode("09876"));
//6.设置节点的关系(从叶子节点开始设置关系)
		linkman.appendChild(name);
		linkman.appendChild(tel);
		addresslist.appendChild(linkman);
		doc.appendChild(addresslist);//文档上保存节点
//7.输出文档的内容
		/**
		 * TransformerFactory-->Transformer(设置编码,transform转换source->result)
		 * DOMSource source = new DOMSource(doc)  输出文档 
		 * StreamResult result = new StreamResult(new File("d:"+File.separator+"345.xml")) 指定输出位置
		  */
		TransformerFactory  tf  = TransformerFactory.newInstance(); //创建TransformerFactory
		Transformer t = null;
		try {
		 t = tf.newTransformer();//创建Transformer

		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		t.setOutputProperty(OutputKeys.ENCODING,"utf-8");//设置编码
		DOMSource source = new DOMSource(doc); //输出文档
		StreamResult result = new StreamResult(new File("d:"+File.separator+"345.xml"));//指定输出位置
		try {
			t.transform(source,result);//输出
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
原文链接:https://www.f2er.com/xml/296083.html

猜你在找的XML相关文章