一、JDOM简介
JDOM是一个开源项目,它基于树型结构,利用纯JAVA的技术对XML文档实现解析、生成、序列化以及多种操作。
JDOM 直接为JAVA编程服务。它利用更为强有力的JAVA语言的诸多特性(方法重载、集合概念以及映射),把SAX和DOM的功能有效地结合起来。
在使用设计上尽可能地隐藏原来使用XML过程中的复杂性。利用JDOM处理XML文档将是一件轻松、简单的事。

输入类,一般用于文档的创建工作
SAXBuilder
DOMBuilder
ResultSetBuilder

org.JDOM.output
输出类,用于文档转换输出
XMLOutputter

SAXOutputter
DomOutputter
JtreeOutputter

1

/**

*  使用JDOM操作(增删改查)XML文档并输入XML文档中

* @author YZB

*/

publicclass JDOMConvert {

publicstaticvoid main(String[] args) {

SAXBuilder saxbuilder=new SAXBuilder();

try {

//构建一个JDOM文档文件

Document doc = saxbuilder.build(new File("student.xml"));

Element root=doc.getRootElement();//获得跟元素

//添加对象

Element eltstu1 = new Element("student");

Element eltname1 = new Element("name");

Element eltage1 = new Element("age");

eltname1.setText("张三");

eltage1.setText("18");

eltstu1.addContent(eltname1);

eltstu1.addContent(eltage1);

eltstu1.setAttribute("id", "01");

root.addContent(eltstu1);

//删除对象

//消除第一个孩子元素

root.removeChild("student");

//得到第一个孩子元素

root.getChild("student").getChild("age").setText("33");

// 输出信息

//输出类

XMLOutputter xop=new XMLOutputter();

//格式化类

Format fmt=Format.getPrettyFormat();

fmt.setIndent("    ");

fmt.setEncoding("gb2312");

xop.setFormat(fmt);

xop.output(doc, System.out);

} catch (JDOMException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

2

/**

* 使用JDOM创建XML文档并输入带控制台

* @author YZB

*/

publicclass JDOMTest {

publicstaticvoid main(String[] args) {

// 构造Document对象

Document doc = new Document();

// 一个XML处理指令

ProcessingInstruction pi = new ProcessingInstruction("xml-stylesheet",

" type='text/xsl' href='student.xsl'");

doc.addContent(pi);

//创建跟节点

Element root = new Element("students");

doc.setRootElement(root);

//添加节点对象

Element eltstu1 = new Element("student");

Element eltname1 = new Element("name");

Element eltage1 = new Element("age");

eltname1.setText("张三");

eltage1.setText("18");

eltstu1.addContent(eltname1);

eltstu1.addContent(eltage1);

eltstu1.setAttribute("id", "01");

root.addContent(eltstu1);

Element eltstu2 = new Element("student");

Element eltname2 = new Element("name");

Element eltage2 = new Element("age");

eltname2.setText("李四");

eltage2.setText("18");

eltstu2.addContent(eltname2);

eltstu2.addContent(eltage2);

eltstu2.setAttribute("id", "02");

root.addContent(eltstu2);

//输出类

XMLOutputter xop=new XMLOutputter();

//格式化类

Format fmt=Format.getPrettyFormat();

fmt.setIndent("    ");

fmt.setEncoding("gb2312");

xop.setFormat(fmt);

try {

xop.output(doc, System.out);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}