本例以Windows, JDK1.7 为基础,来演示使用Java 采用DOM方式来创建XML文件。

XML文件

需要创建的XML效果如下:
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Class>
<Student id="1">
<name>duliu</name>
<age>26</age>
<performance>99</performance>
</Student>
</Class>

示例代码

CreateXML.java 来创建XML文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.devnp.xml.dom;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CreateXML {

public static void main(String[] args) {
// TODO Auto-generated method stub


DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder docBuilder = null;

try {
docBuilder = docFactory.newDocumentBuilder();


} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//根节点
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Class");
doc.appendChild(rootElement);

//创建Student
Element staff = doc.createElement("Student");
rootElement.appendChild(staff);

//设置id属性
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);

//设置Name
Element name = doc.createElement("name");
name.appendChild(doc.createTextNode("duliu"));
staff.appendChild(name);

//设置年纪
Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("26"));
staff.appendChild(age);

//设置成绩
Element performance = doc.createElement("performance");
performance.appendChild(doc.createTextNode("99"));
staff.appendChild(performance);

//写入到文件
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null ;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("D:\\Person-Test\\temp\\class.xml"));

try {
transformer.transform(source, result);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("Create XML with DOM is Success.");
}

}