- src
- com.djh.michael.bean
- User.java
- com.djh.michael.dao
- com.djh.michael.utils- XmlDao.java
- XmlUtils.java
- com.djh.michael.exception
- UserAlreadyExists.java
- UserNotFoundException.java
- com.djh.michael.test
- TestCase.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 + "]";
}
}
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 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 getAllUser(){
List list = new ArrayList();
try {
Document document = XmlUtils.getDocument(path);
Element rootElement = document.getRootElement();
//via Xpath expression to select all the nodes.
List nodes = rootElement.selectNodes("/users/*");
for (int i = 0; nodes!=null && i < nodes.size(); i++) {
User user = new User();
List 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 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 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 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 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 list, User user) {
//via to loop all the options
for (Iterator iter = 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)){
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 list, User user) {
//via to loop all the options
for (Iterator iter = 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() + "");
}
}
}
}
just extends Exception and method.
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
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(new FileOutputStream(path), format);
writer.write(document);
writer.close();
}
}
123
djh
25
USD
200
12.25
456
tk
24
AUD
5000
11.06
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 list = xmlDao.getAllUser();
System.out.println(list);
}
@Test
public void testAddUser(){
User user = new User("789", "lj", 18, "RMB", 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", 30, "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", 18, "RMB", 6000, 9.5);
XmlDao xmlDao = new XmlDao();
xmlDao.deleteUser(user);
}
}
http://www.w3schools.com/xml/xml_xpath.asp