package com.jdom;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import bsh.This;
public class JdomTest {
/**
* 创建xml文档
*/
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("d://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) {
// 创建xml文档
// JdomTest jte = new JdomTest();
// jte.CreateDocument();
// 创建xml解析器
SAXBuilder sb = new SAXBuilder();
// 构造文档对象
Document doc = null;
try {
doc = sb.build("d:/test.xml");
} catch (Exception e) {
e.printStackTrace();
}
// 获取根元素
Element root = doc.getRootElement();
// 获取节点名
String rootName = root.getName();
System.out.println("Type :" + rootName);
Element height = root.getChild("height");
// 获取节点文档内容
System.out.println("Height: " + height.getText());
// 获取节点属性值
System.out.println("State: " + height.getAttributeValue("state"));
}
}