Application construct:Xmldemo:-Src-com.djh.michael.bean
-User.java
-Com.djh.michael.dao
-Xmldao.java-com.djh.michael.utils
-Xmlutils.java
-Com.djh.michael.exception
-Useralreadyexists.java
-Usernotfoundexception.java
-Com.djh.michael.test
-Testcase.java JavaBean:User.java
Package Com.djh.michael.bean;
public class User {private String ID;
private String name;
private int age;
Private String currency;
private int quality;
private double price;
Public User () {super ();
TODO auto-generated Constructor stub} public User (string ID, string name, int age, string currency, int quality,
Double price) {super ();
This.id = ID;
THIS.name = name;
This.age = age;
this.currency = currency;
this.quality = quality;
This.price = Price;
Public String GetId () {return id;
public void SetId (String id) {this.id = ID;
Public String GetName () {return name;
public void SetName (String name) {this.name = name;
public int getage () {return age;
public void Setage (int age) {this.age = age;
Public String getcurrency () {return currency;
} public void Setcurrency (String currency) {this.currency = currency;
public int getquality () {return quality; } public void setquality (int quality) {
this.quality = quality;
Public double GetPrice () {return price;
public void Setprice (double price) {this.price = Price; @Override public String toString () {return "User [id=] + ID +", name= "+ name +", age= "+ Age +", currency=
"+ Currency +", quality= "+ quality +", price= "+ price +"];
}
}
DAO:XmlDAO.java
Package Com.djh.michael.dao;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import org.dom4j.Element;
Import Org.dom4j.Node;
Import Com.djh.michael.bean.User;
Import com.djh.michael.exception.UserAlreadyExists;
Import com.djh.michael.exception.UserNotFoundException;
Import Com.djh.michael.utils.XmlUtils;
public class Xmldao {String path = ' Src/users.xml ';
Private user user = null;
Select one data.
Public User Getoneuser (String id) {try {//get the Document object via class of Utils.
Document document = Xmlutils.getdocument (path);
Element rootelement = Document.getrootelement ();
Select the one record via field of ID.
list<element> list = Rootelement.selectnodes ("/users/user[id=" + ID + "]/*");
if (list!= null) {user = new user ();
} setUser (list, user);
return user;
catch (Documentexception e) {e.printstacktrace ();
return null; }
Get all users data.
Public list<user> Getalluser () {list<user> List = new arraylist<user> ();
try {Document document = Xmlutils.getdocument (path);
Element rootelement = Document.getrootelement ();
Via Xpath expression to select all the nodes.
list<element> nodes = rootelement.selectnodes ("/users/*");
for (int i = 0; Nodes!=null && i < nodes.size (); i++) {User user = new user ();
list<element> usernodes = Nodes.get (i) selectnodes ("/users/user[" + (i + 1) + "]/*");
SetUser (usernodes, user);
List.add (user);
} catch (Documentexception e) {e.printstacktrace ();
} return list;
public boolean addUser (user user) {Boolean result = false;
Try {//get the object of document.
Document document = Xmlutils.getdocument (path);
Element root = Document.getrootelement ();
Judge the user whether if already exists. Node node = root.selectsinglenode ("/users/user[id=" + user.getid () + "]");
if (node!= null) {System.out.println ("User is already exists ...");
throw new Useralreadyexists ("User is already exists ...");
}//add the user element.
Element userelement = root.addelement ("user");
Userelement.addelement ("id"). addtext (User.getid ());
Userelement.addelement ("name"). AddText (User.getname ());
Via add empty character to transfer the none string to string type.
Userelement.addelement ("Age"). AddText (User.getage () + "");
Userelement.addelement ("Currency"). AddText (User.getcurrency ());
Userelement.addelement ("Quality"). AddText (user.getquality () + "");
Userelement.addelement ("Price"). AddText (User.getprice () + "");
Write to file.
Xmlutils.write2document (path, document);
System.out.println ("Add user success ...");
result = true;
}catch (useralreadyexists e) {throw new RuntimeException (e);
catch (Exception e) {e.printstacktrace ();
return result; public boolean updateuser (user user) {Boolean result = FalsE
try {//get the Document Object document = Xmlutils.getdocument (path);
Element root = Document.getrootelement ();
Find there whether if exists user which ready update.
Node node = root.selectsinglenode ("/users/user[id=" + user.getid () + "]");
if (node = = null) {System.out.println ("User not exists ...");
throw new Usernotfoundexception ("The user is not exists which ID is" + user.getid ());
} list<element> List = Root.selectnodes ("/users/user[id=" + user.getid () + "]/*");
UpdateUser (list, user);
Update xmlutils.write2document (path, document);
SYSTEM.OUT.PRINTLN ("Update success ...");
result = true;
}catch (Usernotfoundexception e) {throw new RuntimeException (e);
catch (Exception e) {e.printstacktrace ();
return result;
public boolean deleteuser (user user) {Boolean result = false;
Try {//get the object of document.
Document document = Xmlutils.getdocument (path); Element root = document.Getrootelement ();
In there, you can select the What you like option to filter.
Node node = root.selectsinglenode ("/users/user[id=" + user.getid () + "]");
if (node = null) {throw new Usernotfoundexception ("User not found, please confirm ...");
}//remove the user via itself ' s parent node.
Node.getparent (). Remove (node);
Write to file.
Xmlutils.write2document (path, document);
SYSTEM.OUT.PRINTLN ("Update success ...");
result = true;
}catch (Usernotfoundexception e) {throw new RuntimeException (e);
}catch (Exception e) {e.printstacktrace ();
return result; } private void SetUser (list<element> List, user user) {//via to loop all of the options for (iterator iter = Li St.iterator (); Iter.hasnext ();)
{Node node = (Element) iter.next ();
Get the element tag name and content String name = Node.getname ();
String value = Node.gettext ();
Package data to Bean object.
if ("id". Equals (name)) {User.setid (value);
}if ("Name". Equals (name)) {user.setname (value);
} if ("Age". Equals (name)) {User.setage (Integer.parseint (value));
} if ("Currency". Equals (name)) {user.setcurrency (value);
} if ("Quality". Equals (name)) {user.setquality (Integer.parseint (value));
} if ("Price". Equals (name)) {User.setprice (double.parsedouble (value));
} System.out.println ("@@@" + name + ":" + value); } private void UpdateUser (list<element> List, user user) {//via to loop all the options for (iterator ite R = List.iterator (); Iter.hasnext ();)
{Node node = (Element) iter.next ();
Get the element tag name and content String name = Node.getname ();
String value = Node.gettext ();
Package data to Bean object.
if ("id". Equals (name)) {Node.settext (User.getid ());
} if ("Name". Equals (name)) {Node.settext (User.getname ());
} if ("Age". Equals (name)) {Node.settext (User.getage () + ""); } if ("Currency". Equals (name)) {NODE.SEttext (User.getcurrency ());
} if ("Quality". Equals (name)) {Node.settext (user.getquality () + "");
} if ("Price". Equals (name)) {Node.settext (User.getprice () + "");
}
}
}
}
Exception:UserAlreadyExists.java and Usernotfoundexception.javaJust extends Exception and method.
Utils:XmlUtils.java
Package com.djh.michael.utils;
Import Java.io.FileOutputStream;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import Org.dom4j.io.OutputFormat;
Import Org.dom4j.io.SAXReader;
Import Org.dom4j.io.XMLWriter;
public class Xmlutils {public
static Document getdocument (String path) throws documentexception{
Saxreader reader = new Saxreader ();
Document document = Reader.read (path);
return document;
}
public static void Write2document (String path, document document) throws exception{
//format the XML file
OUTPU Tformat format = Outputformat.createprettyprint ();
Format.setencoding ("Utf-8");
XMLWriter writer = new XMLWriter (new FileOutputStream (path), format);
Writer.write (document);
Writer.close ();
}
XML file (DB): Users.xml
<?xml version= "1.0" encoding= "Utf-8"?>
<users>
<user>
<id>123</id>
<name>djh</name>
<age>25</age>
<currency>USD</currency>
<quality>200</quality>
<price>12.25</price>
</user>
<user>
<id>456</id>
<name>tk</name>
<age>24</age>
< currency>aud</currency>
<quality>5000</quality>
<price>11.06</price >
</user>
</users>
Class of Test:TestCase.java
Package com.djh.michael.test;
Import java.util.List;
Import Org.junit.Test;
Import Com.djh.michael.bean.User;
Import Com.djh.michael.dao.XmlDao;
public class TestCase {@Test public void Testxmldaogetuser () {Xmldao Xmldao = new Xmldao ();
User user = Xmldao.getoneuser ("123");
System.out.println (User.tostring ());
@Test public void Testgetalluser () {Xmldao Xmldao = new Xmldao ();
list<user> list = Xmldao.getalluser ();
SYSTEM.OUT.PRINTLN (list);
@Test public void Testadduser () {User user = new User ("789", "LJ", "6000, 9.5");
Xmldao Xmldao = new Xmldao ();
Boolean result = Xmldao.adduser (user);
SYSTEM.OUT.PRINTLN (result);
@Test public void Testupdate () {User user = new User ("789", "Niu", "HKD", 6000, 9.5);
Xmldao Xmldao = new Xmldao ();
Boolean result = Xmldao.updateuser (user);
SYSTEM.OUT.PRINTLN (result);
@Test public void Testdeleteuser () {User user = new User ("789", "LJ", "6000, 9.5"); Xmldao Xmldao =New Xmldao ();
Xmldao.deleteuser (user); }
}
Xpath Format Reference Link:
Http://www.w3schools.com/xml/xml_xpath.asp