package com.sinan;
import java.io.*;
import org.jdom.*;
import org.jdom.output.*;
public class CreateXML {
/**
* @param args
*/
// 声明XML中所有的元素
Element customer, name, age, sex, address, street, city, district;
public CreateXML() {
// 创建customer元素,并设置为XML文档的根节点
customer = new Element("customer");
Document myDocument = new Document(customer);
// 创建XML文档中的其他元素,并初始化元素名
name = new Element("name");
age = new Element("age");
sex = new Element("sex");
address = new Element("address");
street = new Element("street");
city = new Element("city");
district = new Element("district");
// 给XML文档中的每一个元素添加内容值
name.addContent("Wang Xiao Yue");
age.addContent("24");
sex.addContent("male");
street.addContent("No.1 East Rood,ShangDi");
district.addContent("Hai Dian");
city.addContent("Bei Jing");
// 将street、district和city元素作为子元素,添加到address元素中
address.addContent(street);
address.addContent(district);
address.addContent(city);
// 将address元素作为子元素,添加到customer根元素中
customer.addContent(name);
customer.addContent(age);
customer.addContent(sex);
customer.addContent(address);
try {
// 创建XML文件输出流
XMLOutputter xmlOutputter = new XMLOutputter();
// 创建文件输出流
FileWriter writer = new FileWriter("d:\\customer.xml");
// 设置所创建的XML文档的格式
Format f = Format.getPrettyFormat();
xmlOutputter.setFormat(f);
// 将生成的XML文档写入到"c:\customer.xml"文件中
xmlOutputter.output(myDocument, writer);
xmlOutputter.output(myDocument, System.out);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CreateXML createXML = new CreateXML();
}
}