Dom4j操作XML实战,解析和插入XML实例

本例子是用XML来代替数据库的,XML的每个节点代替数据库一行数据。

直说过程:

XML文件结构:定义了一个名为:User.xml的文件:

<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user id="0001" name="小米" password="xiaomi" birthday="1980-09-03" nickname="小强"/>
</users>

定义一个XML操作的工具类:

获取XML文件路径的方法:

private static String fillpath=XmlUtill.class.getClassLoader().getResource("User.xml").getPath();

但是,由于fillpath的路径名称中包含中文,为了处理这个,需要做中文处理,加上:

    private static String fillpath;
    static {
        fillpath=XmlUtill.class.getClassLoader().getResource("User.xml").getPath();
        try {
            fillpath = URLDecoder.decode(fillpath,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }  
        System.out.println(fillpath);
    }

工具类完整代码:

主要包含:获取Document和写入XML两个操作:

package com.Utill;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlUtill {

    private static String fillpath;
    static {
        fillpath=XmlUtill.class.getClassLoader().getResource("User.xml").getPath();
        try {
            fillpath = URLDecoder.decode(fillpath,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }  
        //System.out.println(fillpath);
    }
    //获取Document
    public static Document getDocument() throws Exception
    {
         SAXReader reader=new SAXReader();
         Document document=reader.read(new File(fillpath));
         return document;
    }
    //将Document写入XML
    public static void writToXml(Document document) throws IOException
    {
        OutputFormat format=OutputFormat.createPrettyPrint();
        XMLWriter writer=new XMLWriter(new FileOutputStream(fillpath),format);
        writer.write(document);
        
        format=OutputFormat.createPrettyPrint();
        writer=new XMLWriter(System.out,format);
        writer.write(document);
    }
}

定义一个POJO:User

package com.domain;

import java.util.Date;

public class User {

    private String id;
    private String name;
    private String password;
    private Date    birthday;
    private String nickname;
    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 String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", password=" + password + ", birthday=" + birthday + ", nickname="
                + nickname + "]";
    }
}

定义一个UserImpl类,用来对xml进行查询,新增操作,模拟数据库的查询和新增操作

package com.dao;

import java.text.SimpleDateFormat;
import org.dom4j.Document;
import org.dom4j.Element;

import com.Utill.XmlUtill;
import com.domain.User;

public class UserDaoImpl {

    public void add(User user)
    {
        try {
            Document document=XmlUtill.getDocument();
            Element root=document.getRootElement();
            
            Element user_tag=root.addElement("user");
            user_tag.addAttribute("id", "0002");
            user_tag.addAttribute("name", "华为");
            user_tag.addAttribute("password","华为");
            user_tag.addAttribute("birthday", user.getBirthday()==null?" ":user.getBirthday().toLocaleString());
            user_tag.addAttribute("nickname", "大强");
            
            XmlUtill.writToXml(document);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    public User find(String name,String password)
    {
        try {

            Document document;
            document = XmlUtill.getDocument();

            Element e=(Element) document.selectSingleNode("//user[@name='"+name+"' and @password='"+password+"']");
            if(e==null)
                return null;
            User user=new User();
            String date=e.attributeValue("birthday");
            if(date==null||date.equals(""))
                user.setBirthday(null);
            else
            {
                //日期转换类
                SimpleDateFormat df=new SimpleDateFormat("yyyy-MM--dd");
                user.setBirthday(df.parse(date));
            }
            
            user.setId(e.attributeValue("id"));
            user.setName(e.attributeValue("name"));
            user.setPassword(e.attributeValue("password"));
            user.setNickname(e.attributeValue("nickname"));
            
            System.out.println(user.toString());
            return user;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

测试类,测试查询和新增功能:

package com.Test;
import java.util.Date;
import org.junit.jupiter.api.Test;
import com.dao.UserDaoImpl;
import com.domain.User;

class UserTest {

    @Test
    void testAdd() {
        User user=new User();
        user.setId("0002");
        user.setName("华为");
        user.setPassword("huawei");
        user.setBirthday(new Date());
        user.setNickname("大强");
        
        UserDaoImpl dao=new UserDaoImpl();
        dao.add(user);
    }
    
    public void TestFind()
    {
        UserDaoImpl dao=new UserDaoImpl();
        dao.find("小米", "xiaomi");
    }

}

 

posted @ 2018-07-07 22:17  美好的明天  阅读(853)  评论(0编辑  收藏  举报