用jdom创建中文的xml文件的方法

时间:2022-01-25 00:53:15

实例如下:

?
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
package test;
 
import java.io.File;
 
public class DOMTest {
    private String outFile = "c:\\abc\\people.xml";
 
    public static void main(String[] args) {
        new DOMTest();
 
    }
 
    public DOMTest() {
        try {
            File file = new File(outFile);
            if(!file.exists()){
                file.createNewFile();
            }
            
            javax.xml.parsers.DocumentBuilder builder = javax.xml.parsers.DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            org.w3c.dom.Document doc = builder.newDocument();
            org.w3c.dom.Element root = doc.createElement("老师");
            org.w3c.dom.Element wang = doc.createElement("苍");
            org.w3c.dom.Element liu = doc.createElement("刘");
 
            wang.appendChild(doc.createTextNode("我是苍老师"));
            root.appendChild(wang);
            root.appendChild(liu);
            doc.appendChild(root);
            
            javax.xml.transform.Transformer transformer = javax.xml.transform.TransformerFactory.newInstance()
                    .newTransformer();
            transformer.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, "gb2312");
            transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
            transformer.transform(new javax.xml.transform.dom.DOMSource(doc),
                    new javax.xml.transform.stream.StreamResult(outFile));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

以上这篇用jdom创建中文的xml文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。