##创建XML文档
/**
*
*/
package com.xiaobian.dom.jdom;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.*;
import org.jdom.output.XMLOutputter;
/**
* @author xiaobian
*
*/
public class Jdom {
public Jdom() {
super();
}
public void CreateDocument(){
//创建根元素
Element eRoot = new Element("person");
//为根元素创建属性
eRoot.setAttribute(new Attribute("id", "13562986536525458954"));
//为根元素添加注释内容
eRoot.addContent(new Comment("A Person"));
//创建根元素的子元素
Element name = new Element("name");
//为此元素创建内容
name.addContent("xiaobian");
//创建根元素的子元素
Element sex = new Element("sex");
sex.addContent("Male");
//创建根元素的子元素
Element year = new Element("year");
year.addContent("1982");
//创建根元素的子元素
Element age = new Element("age");
age.addContent("26");
//创建根元素的子元素
Element height = new Element("height");
height.setAttribute("state","China");
height.addContent("178cm");
eRoot.addContent(name);
eRoot.addContent(sex);
eRoot.addContent(year);
eRoot.addContent(age);
eRoot.addContent(height);
Document d = new Document(eRoot);
//定义输出
XMLOutputter outputter = new XMLOutputter();
//输出流
FileWriter writer = null;
try {
//输出到控制台
outputter.output(d, System.out);
} catch (java.io.IOException e) {
e.printStackTrace();
}
try {
//创建文件流
writer = new FileWriter("c://test.xml");
} catch (IOException e) {
e.printStackTrace();
}
try {
//输出到Xml文件
outputter.output(d, writer);
} catch (IOException e) {
e.printStackTrace();
}
try {
//关闭文件流
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
Jdom jdom = new Jdom();
//测试
jdom.CreateDocument();
}
}
##读取XML文档
public static void main(String[] args) throws Exception{
SAXBuilder sb=new SAXBuilder();
Document doc=sb.build("c:/test.xml"); //构造文档对象
Element root=doc.getRootElement(); //获取根元素
String rootName = root.getName();
System.out.println("Type :"+rootName);
Element name = root.getChild("name");
System.out.println("Name: "+name.getText());
Element sex = root.getChild("sex");
System.out.println("Sex: "+sex.getText());
Element year = root.getChild("year");
System.out.println("Birth: "+year.getText());
Element age = root.getChild("age");
System.out.println("Age: "+age.getText());
Element height = root.getChild("height");
System.out.println("Height: "+height.getText());
System.out.println("State: "+height.getAttributeValue("state"));
}