class LogJdom
{
private static final String LOG = "log.xml";
private Element root = new Element("Log");
private Element user = new Element("user");
private Element log = new Element("log");
private Element time = new Element("time");
Document doc = new Document(root);
Format format = Format.getCompactFormat();
XMLOutputter XMLOut = null;
LogJdom() throws Exception //为了简单,没有处理异常
{
format.setEncoding("gbk");
format.setIndent(" ");
XMLOut = new XMLOutputter(format);
XMLOut.output(doc, new FileOutputStream(LOG));
}
public void addUserNode(String name) throws Exception
{
user =new Element("user");
user.setAttribute("name",name);
doc.getRootElement().addContent(user);
XMLOut.output(doc, new FileOutputStream(LOG));
}
public void addLog(String name,String alog) throws Exception
{
boolean hasnouser = true;
List list = doc.getRootElement().getChildren("user"); //得到所有子世节点
Element e = null;
for(int i=0;i<list.size();i++)
{
e = (Element)list.get(i);
if(e.getAttributeValue("name")==name)
{
hasnouser = false;
break;
}
}
if(hasnouser)
{
addUserNode(name);
addLog(name,alog);
}else
{
log = new Element("log");
log.setText(alog);
time = new Element("time");
time.setText(new Date().toString());
e.addContent(log);
e.addContent(time);
XMLOut.output(doc, new FileOutputStream(LOG));
}
}
public void delNode(String name) throws Exception
{
List list = doc.getRootElement().getChildren("user");
System.out.println("------"+list);
for(int i=0;i<list.size();i++)
{
Element e = (Element)list.get(i);
if(e.getAttributeValue("name")==name)
{
list.remove(i); //删除此节点!
}
}
XMLOut.output(doc, new FileOutputStream(LOG));
}
public void read() throws Exception
{
SAXBuilder builder = new SAXBuilder();
Document read_doc = builder.build(LOG);
Element Log = read_doc.getRootElement();
List list = Log.getChildren("user");
for(int i = 0;i < list.size();i++)
{
Element e = (Element)list.get(i);
System.out.println("user:"+e.getAttributeValue("name"));
String log = e.getChildText("log");
String time = e.getChildText("time");
System.out.println(" log:"+log);
System.out.println(" time:"+time);
}
}
}
public class TestJDom
{
public static void main(String[] args) throws Exception
{
LogJdom log = new LogJdom();
System.out.println("----------------------");
log.addUserNode("yidon");
log.addUserNode("andrwu");
log.addLog("yidon","two");
log.addLog("tom","leave the WWW!");
log.addLog("tom","leave the WWW!");
log.read();
log.addLog("tt","leave the WWW!");
log.delNode("tt"); //新增后又被删除就不会显示出来。
}
}
输出:
<?xml version="1.0" encoding="gbk"?>
<Log>
<user name="yidon">
<log>two</log>
<time>Wed Aug 10 23:09:04 CST 2005</time>
</user>
<user name="andrwu" />
<user name="tom">
<log>leave the WWW!</log>
<time>Wed Aug 10 23:09:04 CST 2005</time>
<log>leave the WWW!</log>
<time>Wed Aug 10 23:09:04 CST 2005</time>
</user>
</Log>