
/*

?*?創建日期?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();

????????}


????}

}

