事先需要从这里下载:http://www.jdom.org/dist/binary/ jdom api,导入build目录的 jdom.jar

JdomRWXML.java 源码:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

public class JdomRWXML {
 public void BuildXMLDoc() throws IOException, JDOMException {
  // 创建根节点 list;
  Element root = new Element("list");
  // 将根节点添加到文档中;
  Document Doc = new Document(root);
  // 此处 for 循环可替换成 遍历 数据库表的结果集操作;
  for (int i = 0; i < 5; i++) {
   // 创建新节点 company;
   Element elements = new Element("company");
   // 给 company 节点添加属性 id;
   elements.setAttribute("id", "" + i);
   // 给 company 节点添加子节点并赋值
   elements
     .addContent(new Element("company_name").setText("name" + i));
   elements.addContent(new Element("company_email").setText("name" + i
     + "@163.com"));
   // 给父节点list添加company子节点;
   root.addContent(elements);
  }
  XMLOutputter XMLOut = new XMLOutputter();
  // 输出company_list.xml文件;
  XMLOut.output(Doc, new FileOutputStream("company_list.xml"));
 }

 public void ReadXMLDoc() throws IOException, JDOMException {
  SAXBuilder sb = new SAXBuilder();// 建立构造器
  Document doc = sb.build(new FileInputStream("company_list.xml"));// 读入指定文件
  Element root = doc.getRootElement();// 获得根节点
  List<?> list = root.getChildren();// 将根节点下的所有子节点放入List中
  for (int i = 0; i < list.size(); i++) {
   System.out.println("---------------------------");
   Element item = (Element) list.get(i);// 取得节点实例
   String id = item.getAttribute("id").getValue();// 取得属性值
   System.out.println("id-->" + id);

   Element sub1 = item.getChild("company_name");// 取得当前节点的字节点
   String company_name = sub1.getText();// 取得当前节点的值
   System.out.println("company_name-->" + company_name);

   Element sub2 = item.getChild("company_email");
   String company_email = sub2.getText();
   System.out.println("company_email-->" + company_email);
  }

 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try {
   JdomRWXML jdomRWXML = new JdomRWXML();

   System.out.println("--------BuildXMLDoc----------");
   jdomRWXML.BuildXMLDoc();

   System.out.println("--------ReadXMLDoc----------");
   jdomRWXML.ReadXMLDoc();

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}