import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
public class XmlDo
{
//============================================
//创建XML文档
//============================================
public void BuildXML() throws Exception
{
//定义变量
Element root, student, number, name, age;
//生成根元素:student-info
root = new Element("student-info");
//将根元素植入文档doc中
Document doc = new Document(root);
//循环子结点
for(int i=0;i<10;i++)
{
//生成元素:student,该元素中将包含元素number,name,age
student = new Element("student");
number = new Element("test");
name = new Element("test");
age = new Element("test");
//设置各结点的值
number.setText("test");
name.setText("test");
age.setText("test");
//向student结点添加子结点
student.addContent(number);
student.addContent(name);
student.addContent(age);
//把student结点添加到根结点上
root.addContent(student);
}
//创建格式化对象
Format format = Format.getCompactFormat();
//设置xml文件的字符为gb2312
format.setEncoding("gb2312");
//设置xml文件的缩进为4个空格
format.setIndent(" ");
//在元素后换行,每一层元素缩排四格
XMLOutputter XMLOut = new XMLOutputter(format);
//输出xml文档
XMLOut.output(doc, new FileOutputStream("studentinfo.xml"));
}
//============================================
//解析XML文档
//============================================
public void ParseXML() throws Exception
{
//注册解析器
SAXBuilder builder = new SAXBuilder();
//要读取的xml文档
File file = new File("studentinfo.xml");
//读取XML文档
Document doc = builder.build(file);
//得到根结点
Element root = doc.getRootElement();
//把根结点的子结点取出以list型式存
List list = root.getChildren();
//列出xml文档内容
//readXML(list,root.getName());
readXML(list,root.getName(),0);
}
//============================================
//递归列出所有结点的函数
//============================================
public void readXML(List list,String root,int step) throws Exception
{
//父结点前空格
for(int j=0;j");
//当前结点的子结点个数循环
for(int i=0;i0)
{
//调用函数本身
//readXML(tlist,item.getName()+"["+i+"]");
readXML(tlist,item.getName(),step+1);
}
//子结点没有子结点时,输出结点内容及名称
else
{
//输出对齐空格
for(int j=0;j
{
System.out.print(" ");
}
System.out.println(""+item.getText()+"");
}
}
//输出父结点对齐空格
for(int j=0;j");
}
//============================================
//main方法
//============================================
public static void main(String[] args) throws Exception
{
//创建对象
XmlDo xml = new XmlDo();
//创建xml文档
System.out.println("正在创建XML文档 ...");
xml.BuildXML();
System.out.println("XML文档创建成功...");
//读取xml文档
System.out.println("正在读取XML文档...");
xml.ParseXML();
System.out.println("XML文档读取完毕...");
}
}