jdom生成xml文件

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

 

import org.jdom.Attribute;

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.output.XMLOutputter;

/**

 * jdom操作生成一个xml文件

 * @author 王强松

 * @time 2012-4-22

 *

 */

public class WriteXML {

public static void main(String[] args) {

Element addresslist = new Element("addresslist"); //定义根节点

Element linkman = new Element("linkman"); //定义linkman节点

Element name = new Element("name");//定义mane节点

Element email = new Element("email");//定义email节点

Attribute id = new Attribute("id","001"); //定义属性id

Document doc = new Document(addresslist); //声明第一个document对象

name.setText("ALEX");

email.setText("muguku@qq.com");

name.setAttribute(id);

linkman.addContent(name);

linkman.addContent(email);

addresslist.addContent(linkman);

XMLOutputter out = new XMLOutputter(); //用来输出xml文件

out.setFormat(out.getFormat().setEncoding("UTF-8"));//设置输出的编码

try {

FileOutputStream file = new FileOutputStream("D:"+File.separator+"address.xml");

out.output(doc, file);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

jdom读取xml文件
import java.io.File;
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;
 
/**
 * 用jdom读取xml文件中的内容
 * @author 王强松
 * @time 2012-4-22
 */
public class ReadXML {
 
public static void main(String[] args) throws Exception{
SAXBuilder sax = new SAXBuilder();//建立SAX解析
Document read_doc = sax.build("D:"+File.separator+"address.xml");//找到Document
Element addresslist = read_doc.getRootElement();//读取根元素
List list = addresslist.getChildren("linkman");//获得全部linkman元素
for (int i = 0; i < list.size(); i++) {
Element linkman = (Element) list.get(i);//取出一个linkman元素
String name = linkman.getChildText("name");
String id = linkman.getChild("name").getAttributeValue("id");
String email = linkman.getChildText("email");
System.out.println("--------联系人------------");
System.out.println("姓名:"+name);
System.out.println("ID:"+id);
System.out.println("邮箱:"+email);
System.out.println("-------------------------");
}
 
}
 
}