/*
* 创建日期 2005-2-15
*/
package com.tiantian.xmlguestbook;//com.tiantian
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.*;
import java.io.*;
/**
* @author tiantian
*/
public class XMLguestbookBean {
public static void main(String[] args) {
XMLguestbookBean exam = new XMLguestbookBean();//声明XMLguestbookBean的一个实例
exam.addmessage("james", "202.11.223.22", "hahah");//增加一个留言,测试
}
public Element root = null;//定义根
public XMLguestbookBean() {
//空的构造函数
}
private void addmessage(String name, String ip, String content) {
try {
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build("guestbook.xml");
root = doc.getRootElement();//取得根元素
Element newMessage = new Element("message");
Element newName = new Element("name");
Element newContent = new Element("content");
Element newIp = new Element("ip");
newName.setText(name); //填入名字
newContent.setText(content);//填入设置
newIp.setText(ip);//填入IP
newMessage.addContent(newName);//添加名字到message
newMessage.addContent(newIp);//添加ip地址到message
newMessage.addContent(newContent);//添加留言内容到message
root.addContent(newMessage);//把message添加到根上
Format format = Format.getCompactFormat();
format.setEncoding("gb2312"); //设置xml文件的字符为gb2312
format.setIndent(" ");
XMLOutputter XMLOut = new XMLOutputter(format);//在元素后换行,每一层元素缩排四格
XMLOut.output(doc, new FileOutputStream("guestbook.xml"));//输出到文件
} catch (FileNotFoundException e) {
// 文件未找到
e.printStackTrace();
} catch (JDOMException e) {
// JDOM异常
e.printStackTrace();
} catch (IOException e) {
// IO异常
e.printStackTrace();
}
}
}