1 import javax.xml.parsers.DocumentBuilder;
2 import javax.xml.parsers.DocumentBuilderFactory;
3 import javax.xml.transform.OutputKeys;
4 import javax.xml.transform.Transformer;
5 import javax.xml.transform.TransformerFactory;
6 import javax.xml.transform.dom.DOMSource;
7 import javax.xml.transform.stream.StreamResult;
8
9 import org.w3c.dom.Document;
10 import org.w3c.dom.Element;
11
12 public class DOMTest {
13 private String inFile = "D:\test.xml";
14 private String outFile = "D:\test.xml";
15
16 public static void main(String[] args) {
17 new DOMTest();
18 }
19
20 public DOMTest() {
21 try {
22 //1、获取DOM解析器工厂,以便产生解析器;2、获取DOM解析器,以便解析DOM
23 DocumentBuilder builder = DocumentBuilderFactory
24 .newInstance().newDocumentBuilder();
25 Document doc = builder.newDocument();
26 //创建元素
27 Element root = doc.createElement("person");
28 Element a = doc.createElement("name");
29 Element b = doc.createElement("age");
30 //向指定元素节点中增加子元素节点或增加元素到子节点
31 a.appendChild(doc.createTextNode("小白"));
32 b.appendChild(doc.createTextNode("18岁"));
33 root.appendChild(a);
34 root.appendChild(b);
35 doc.appendChild(root);
36 //设置后要把DOM写回XML文件
37 Transformer transformer = TransformerFactory
38 .newInstance().newTransformer();
39 //编码指定Transformer应该使用的首选字符编码,将字符序列作为字节序列进行编码
40 transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
41 //缩进指定Transformer是否可以添加额外的空白,同时输出
42 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
43 transformer.transform(new DOMSource(doc), new StreamResult(outFile));
44 } catch (Exception e) {
45 System.out.println(e.getMessage());
46 }
47 }