使用dom4j对XML文件进行增删改查

时间:2022-04-15 07:44:51

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myxml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 *
 * @author LiNing
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws UnsupportedEncodingException {
        // TODO code application logic here
        //createXML();
        Information info=new Information();
        info.setTelephone("15940969384");
        info.setEmail("liningwangyi@163.com");

        User user=new User();
        user.setID(2);
        user.setInfo(info);
        user.setPassword("lili");
        user.setUserName("lil");

        User u=seleUser("users",info);
            if(u!=null)
                System.out.println("用户名:"+u.getUserName()+"密码:"+u.getPassword());
    }

    public static void createXML(){
        Document doc=DocumentHelper.createDocument();
        Element users=doc.addElement("users");
        users.addComment("这是一个用户信息存储表");
       
        Element user=users.addElement("user");
        user.addComment("用户信息");

        user.addAttribute("ID", "1");

        Element username=user.addElement("username");
        username.setText("李宁");

        Element password=user.addElement("password");
        password.addText("williams");

        Element info=user.addElement("information");

        Element tel=info.addElement("telephone");
        tel.setText("15940969384");

        Element email=info.addElement("email");
        email.setText("liningwangyi@163.com");

        OutputFormat format=OutputFormat.createPrettyPrint();
        format.setEncoding("GBK");
        format.setTrimText(true);
        try {
             XMLWriter xw = new XMLWriter(new FileOutputStream(new File("src/users.xml")),format);
            //XMLWriter xw = new XMLWriter(new FileWriter(new File("src/users.xml")),format);
             /**
              * 使用FileWriter会生成中文乱码
              */
            xw.write(doc);
            xw.close();
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static boolean addUser(String filename,User user) throws DocumentException{
        boolean freq=false;
        Document doc=new SAXReader().read(new File("src/users.xml"));
        if(doc!=null)
        {
           List li=doc.selectNodes("/users/user/@ID");
           Iterator it=li.iterator();
           LinkedList<Integer> lkl=new LinkedList<Integer>();
           while(it.hasNext())
           {
               Attribute attribute = (Attribute)it.next();
                lkl.add(Integer.valueOf(attribute.getText()));
           }
           Collections.sort(lkl);
           int count =lkl.getLast()+1;

           Element user2=doc.getRootElement().addElement("user");
        user2.addComment("用户信息");

        user2.addAttribute("ID", count+"");

        Element username=user2.addElement("username");
        username.setText(user.getUserName());

        Element password=user2.addElement("password");
        password.addText(user.getPassword());

        Element info=user2.addElement("information");

        Element tel=info.addElement("telephone");
        tel.setText(user.getInfo().getTelephone());

        Element email=info.addElement("email");
        email.setText(user.getInfo().getEmail());

        OutputFormat format=OutputFormat.createPrettyPrint();
        format.setEncoding("GBK");
        format.setTrimText(true);
        try {
             XMLWriter xw = new XMLWriter(new FileOutputStream(new File("src/"+filename+".xml")),format);
            //XMLWriter xw = new XMLWriter(new FileWriter(new File("src/users.xml")),format);
             /**
              * 使用FileWriter会生成中文乱码
              */
            xw.write(doc);
            freq=true;
            xw.close();
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
          
        }
        return freq;
    }

    public static boolean modifyUser(String fileName,User user) throws UnsupportedEncodingException{
        boolean freq=false;
        Document doc=null;
        try {
             doc= new SAXReader().read(new File("src/users.xml"));
        } catch (DocumentException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        int id=user.getID();
        List li=doc.getRootElement().elements("user");
        Iterator it=li.iterator();
        while(it.hasNext())
        {
            Element el=(Element)it.next();
            int f=Integer.valueOf(el.attribute("ID").getText());
            if(id==f)
            {
                Attribute a=(Attribute)el.attribute("ID");
                a.setText(user.getID()+"");
                Element username=el.element("username");
                username.setText(user.getUserName());
                Element password=el.element("password");
                password.setText(user.getPassword());

                Element info=el.element("information");
                Element tel=info.element("telephone");
                tel.setText(user.getInfo().getTelephone());
                Element email=info.element("email");
                email.setText(user.getInfo().getEmail());
               
            }
        }

        OutputFormat format=OutputFormat.createPrettyPrint();
        format.setEncoding("GBK");
        try {
            XMLWriter xw = new XMLWriter(new FileOutputStream(new File("src/" + fileName + ".xml")),format);
            freq=true;
            xw.write(doc);
            xw.close();
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        return freq;
    }

    public static boolean deleUser(String fileName,User user) throws UnsupportedEncodingException{
    boolean freq=false;
    Document doc=null;
        try {
            doc = new SAXReader().read(new File("src/users.xml"));
        } catch (DocumentException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    int id=user.getID();
    List li=doc.getRootElement().elements("user");
    Iterator it=li.iterator();
    while(it.hasNext())
    {
        Element el=(Element)it.next();
        Element parent=el.getParent();
        int f=Integer.valueOf(el.attribute("ID").getText());
        if(id==f)
        {
            parent.remove(el);
        }
        else if(id<f)
        {
            el.attribute("ID").setText(""+(f-1));
        }
    }

    OutputFormat format=OutputFormat.createPrettyPrint();
    format.setEncoding("GBK");
        try {
            XMLWriter xw = new XMLWriter(new FileOutputStream(new File("src/" + fileName + ".xml")),format);
            xw.write(doc);
            xw.close();
            freq=true;
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    return freq;
   }

    public static User seleUser(String fileName,int id){
        Document doc=null;
        User user=null;
        try {
            doc = new SAXReader().read(new File("src/users.xml"));
        } catch (DocumentException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        List li=doc.getRootElement().elements("user");
        Iterator it=li.iterator();
        while(it.hasNext())
        {
            Element el=(Element)it.next();
            int f=Integer.valueOf(el.attribute("ID").getText().trim());
            if(id==f)
            {
                String username=el.element("username").getText();
                String password=el.element("password").getText();
                Element info=el.element("information");
                String tel=info.element("telephone").getText();
                String email=info.element("email").getText();

                Information information=new Information();
                information.setTelephone(tel);
                information.setEmail(email);

                user=new User();
                user.setID(1);
                user.setPassword(password);
                user.setUserName(username);
                user.setInfo(information);
            }
        }
            return user;
    }

    public static User seleUser(String fileName,String username){
        Document doc=null;
        User user=null;
        try {
            doc = new SAXReader().read(new File("src/users.xml"));
        } catch (DocumentException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        List li=doc.getRootElement().elements("user");
        Iterator it=li.iterator();
        while(it.hasNext())
        {
            Element el=(Element)it.next();
            String str=el.element("username").getTextTrim();
            if(str.equals(username))
            {
                int id=Integer.valueOf(el.attribute("ID").getText().trim());
                String password=el.element("password").getText();
                Element info=el.element("information");
                String tel=info.element("telephone").getText();
                String email=info.element("email").getText();

                Information information=new Information();
                information.setTelephone(tel);
                information.setEmail(email);

                user=new User();
                user.setID(id);
                user.setPassword(password);
                user.setUserName(str);
                user.setInfo(information);
            }
        }
            return user;
    }

    public static User seleUser(String fileName,String password,boolean bl){
        Document doc=null;
        User user=null;
        try {
            doc = new SAXReader().read(new File("src/users.xml"));
        } catch (DocumentException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        List li=doc.getRootElement().elements("user");
        Iterator it=li.iterator();
        while(it.hasNext())
        {
            Element el=(Element)it.next();
            String str=el.element("password").getTextTrim();
            if(str.equals(password))
            {
                int id=Integer.valueOf(el.attribute("ID").getText().trim());
                String username=el.element("username").getText();
                Element info=el.element("information");
                String tel=info.element("telephone").getText();
                String email=info.element("email").getText();

                Information information=new Information();
                information.setTelephone(tel);
                information.setEmail(email);

                user=new User();
                user.setID(id);
                user.setPassword(password);
                user.setUserName(str);
                user.setInfo(information);
            }
        }
            return user;
    }

    public static User seleUser(String fileName,Information info){
        Document doc=null;
        User user=null;
        try {
            doc = new SAXReader().read(new File("src/users.xml"));
        } catch (DocumentException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        List li=doc.getRootElement().elements("user");
        Iterator it=li.iterator();
        while(it.hasNext())
        {
            Element el=(Element)it.next();
            Element information=el.element("information");
            String tel=information.element("telephone").getText().trim();
            String email=information.element("email").getText().trim();
            if((tel.equals(info.getTelephone()))&&(email.equals(info.getEmail())))
            {
                int id=Integer.valueOf(el.attribute("ID").getText().trim());
                String password=el.element("password").getText();
                String username=el.element("username").getText().trim();

                user=new User();
                user.setID(id);
                user.setPassword(password);
                user.setUserName(username);
                user.setInfo(info);
            }
        }
            return user;
    }
}