<pre class="java" name="code">/*jdom包的结构包括:
org.jdom 包含了所有的xml文档要素的java类
org.jdom.adapters 包含了与dom适配的java类
org.jdom.filter 包含了xml文档的过滤器类
org.jdom.input 包含了读取xml文档的类
org.jdom.output 包含了写入xml文档的雷
org.jdom.transform 包含了将jdomxml文档接口转换为其他xml文档接口
org.jdom.xpath 包含了对xml文档xpath操作的类
*/
/*
*用jdom写入xml文件的例子
*/
import java.io.*;
import org.jdom.*;
import org.jdom.output.*;
public class WriteXML{
public void BuildXML() throws Exception{
Element root, student, number, name, age;
Attribute attr;
root = new Element("student-info"); //生成根元素:student-info
Document doc = new Document(root); //将根元素植入文档doc中
//生成第一个student
student = new Element("student"); //生成元素:student,该元素中将包含元素number,name,age
attr = new Attribute("type", "china");//增加属性
student.setAttribute(attr);
number = new Element("number");
name = new Element("name");
age = new Element("age");
number.setText("001");
name.setText("peter");
age.setText("24");
student.addContent(number);
student.addContent(name);
student.addContent(age);
root.addContent(student);
//生成第二个student,简化子节点的构造方式
student = new Element("student"); //生成元素:student,该元素中将包含元素number,name,age
student.setAttribute(new Attribute("type", "usa"));
student.addContent(new Element("number").setText("002"));
student.addContent(new Element("name").setText("scott"));
student.addContent(new Element("age").setText("20"));
root.addContent(student);
Format format = Format.getCompactFormat();
format.setEncoding("gb2312"); //设置xml文件的字符为gb2312
format.setIndent(" "); //设置xml文件的缩进为4个空格
XMLOutputter XMLOut = new XMLOutputter(format);//在元素后换行,每一层元素缩排四格
XMLOut.output(doc,new FileOutputStream("studentinfo.xml"));
}
public static void main(String[] args) throws Exception
{
WriteXML w = new WriteXML();
System.out.println("Now we build an XMLdocument.....");
w.BuildXML();
System.out.println("finished!");
}
}
<pre class="java" name="code">/*
*用jdom读取xml文档的例子
*/
import org.jdom.output.*;
import org.jdom.input.*;
import org.jdom.*;
import java.io.*;
import java.util.*;
public class ReadXML
{
public static void main(String[] args) throws Exception
{
SAXBuilder builder = new SAXBuilder();
Document read_doc = builder.build("studentinfo.xml");
Element stu = read_doc.getRootElement();
List list = stu.getChildren("student");
for(int i=0;i<list.size();i++)
{
Element e = (Element)list.get(i);
System.out.println("---------STUDENT--------------");
System.out.println("type:" + e.getAttributeValue("type"));
System.out.println("NUMBER:" + e.getChildText("number"));
System.out.println("NAME:" + e.getChildText("name"));
System.out.println("AGE:" + e.getChildText("age"));
System.out.println("------------------------------");
}
}
}
<?xml version="1.0" encoding="gb2312"?>
<student-info>
<student>
<number>001</number>
<name>peter</name>
<age>24</age>
</student>
</student-info>