数据库:XML,解析Dom4J

Posted 学海无涯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据库:XML,解析Dom4J相关的知识,希望对你有一定的参考价值。

package com.itheima.util;

import java.io.FileOutputStream;
import java.net.URL;

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

public class Dom4JUtil {
    private static String xmlRealpath;
    static{
        ClassLoader cl = Dom4JUtil.class.getClassLoader();
        URL url = cl.getResource("users.xml");
        xmlRealpath = url.getPath();
    }
    
    public static Document getDocument() throws Exception{
        SAXReader reader = new SAXReader();
//        return reader.read("src/users.xml");//错误
        return reader.read(xmlRealpath);
    }
    public static void write2xml(Document document) throws Exception{
        XMLWriter writer = new XMLWriter(new FileOutputStream(xmlRealpath), OutputFormat.createPrettyPrint());
        writer.write(document);
        writer.close();
    }
}
package com.itheima.dao.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.util.Dom4JUtil;

public class UserDaoXmlImpl implements UserDao {

    public User findByUsername(String username) {
        try {
            Document doc = Dom4JUtil.getDocument();
//            List<Node> userNodes = doc.selectNodes("//user");
            Node node = doc.selectSingleNode("//user[@username=‘"+username+"‘]");
            if(node==null)
                return null;
            
            String xmlBirthday = node.valueOf("@birthday");
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday = df.parse(xmlBirthday);
            
            User user = new User(node.valueOf("@username"), node.valueOf("@password"), node.valueOf("@email"), birthday);
            return user;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //<user username="abc" password="123" email="[email protected]" birthday="1980-10-01"/>
    public void save(User user) {
        try {
            Document doc = Dom4JUtil.getDocument();
            Element root = doc.getRootElement();
            root.addElement("user")
                .addAttribute("username", user.getUsername())
                .addAttribute("password", user.getPassword())
                .addAttribute("email", user.getEmail())
                .addAttribute("birthday", user.getBirthday().toLocaleString());
            Dom4JUtil.write2xml(doc);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public User findUser(String username, String password) {
        try {
            Document doc = Dom4JUtil.getDocument();
//            List<Node> userNodes = doc.selectNodes("//user");
            Node node = doc.selectSingleNode("//user[@username=‘"+username+"‘ and @password=‘"+password+"‘]");
            if(node==null)
                return null;
            
            String xmlBirthday = node.valueOf("@birthday");
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday = df.parse(xmlBirthday);
            
            User user = new User(node.valueOf("@username"), node.valueOf("@password"), node.valueOf("@email"), birthday);
            return user;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
package com.itheima.dao.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.util.Dom4JUtil;

public class UserDaoXmlImpl implements UserDao {

    public User findByUsername(String username) {
        try {
            Document doc = Dom4JUtil.getDocument();
//            List<Node> userNodes = doc.selectNodes("//user");
            Node node = doc.selectSingleNode("//user[@username=‘"+username+"‘]");
            if(node==null)
                return null;
            
            String xmlBirthday = node.valueOf("@birthday");
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday = df.parse(xmlBirthday);
            
            User user = new User(node.valueOf("@username"), node.valueOf("@password"), node.valueOf("@email"), birthday);
            return user;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //<user username="abc" password="123" email="[email protected]" birthday="1980-10-01"/>
    public void save(User user) {
        try {
            Document doc = Dom4JUtil.getDocument();
            Element root = doc.getRootElement();
            root.addElement("user")
                .addAttribute("username", user.getUsername())
                .addAttribute("password", user.getPassword())
                .addAttribute("email", user.getEmail())
                .addAttribute("birthday", user.getBirthday().toLocaleString());
            Dom4JUtil.write2xml(doc);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public User findUser(String username, String password) {
        try {
            Document doc = Dom4JUtil.getDocument();
//            List<Node> userNodes = doc.selectNodes("//user");
            Node node = doc.selectSingleNode("//user[@username=‘"+username+"‘ and @password=‘"+password+"‘]");
            if(node==null)
                return null;
            
            String xmlBirthday = node.valueOf("@birthday");
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday = df.parse(xmlBirthday);
            
            User user = new User(node.valueOf("@username"), node.valueOf("@password"), node.valueOf("@email"), birthday);
            return user;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
package com.itheima.test;

import static org.junit.Assert.*;

import java.util.Date;

import org.junit.Test;

import com.itheima.domain.User;
import com.itheima.exception.UserHasExistException;
import com.itheima.service.BusinessService;
import com.itheima.service.impl.BusinessServiceImpl;

public class BusinessServiceImplTest {
    private BusinessService s = new BusinessServiceImpl();
    @Test
    public void testRegist() throws UserHasExistException {
        User user = new User("wzhting", "123", "[email protected]", new Date());
        s.regist(user);
    }
    @Test(expected=com.itheima.exception.UserHasExistException.class)
    public void testRegist1() throws UserHasExistException {
        User user = new User("wzhting", "123", "[email protected]", new Date());
        s.regist(user);
    }
    @Test
    public void testLogin() {
        User user = s.login("wzhting", "123");
        assertNotNull(user);
        user = s.login("wzhting", "111");
        assertNull(user);
        user = s.login("asf", "111");
        assertNull(user);
    }

}
package com.itheima.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

public class BeanUtil {
    //把请求参数封装到指定的JavaBean中
    public static <T> T fillBean(HttpServletRequest request,Class<T> clazz){
        try {
            T bean = clazz.newInstance();
            BeanUtils.populate(bean, request.getParameterMap());
            return bean;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

以上是关于数据库:XML,解析Dom4J的主要内容,如果未能解决你的问题,请参考以下文章

使用 dom4j 解析XML

Dom4j工具j解析XML原理和示例代码

dom4j组装xml 以及解析xml

java中采用dom4j解析xml文件

使用dom4j创建和解析xml文件

XML——XML解析之DOM4J