博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java使用DOM4J对XML文件进行增删改查操作
阅读量:4463 次
发布时间:2019-06-08

本文共 8581 字,大约阅读时间需要 28 分钟。

Java进行XML文件操作,代码如下:

package com.founder.mrp.util;import java.io.File;import java.util.ArrayList;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.Node;import com.founder.mrp.domain.ClientLoginUser;import com.founder.mrp.util.md5.MD5;public class XMLOperateUser {        /*     * 查询全部xml     * */    public static List
ListClinetLoginUser(String appDir) throws Exception{ File dir = new File(appDir+"\\persons.xml"); if (!dir.exists()) { dir.createNewFile(); Document dom = DocumentHelper.createDocument(); Element root = dom.addElement("persons"); String dirpath = dir+""; UtilsForXML.writeToXML(dom, dirpath); } String dirPath = dir+""; Document dom = UtilsForXML.getDocument(dirPath); Element root = dom.getRootElement(); List
persons = new ArrayList
(); List list = root.elements(); for (int i = 0; i < list.size(); i++) { Element person = (Element) list.get(i); ClientLoginUser c = new ClientLoginUser(); String id = person.attributeValue("id"); c.setId(Integer.parseInt(id)); List ll = person.elements(); for (int j = 0; j < ll.size(); j++) { Element element = (Element) ll.get(j); if ("publishername".equals(element.getName())) { String publisherName = element.getText(); c.setPublisherName(publisherName); } if ("serverurl".equals(element.getName())) { String serverurl = element.getText(); c.setServerUrl(serverurl); } if ("username".equals(element.getName())) { String username = element.getText(); c.setUserName(username); } if ("password".equals(element.getName())) { String password = element.getText(); c.setPassword(password); } } persons.add(c); } return persons; } /* * 根据person的属性id查询xml * */ public static ClientLoginUser QueryClinetLoginUserById(String appDir,int id) throws Exception{ File dir = new File(appDir+"\\persons.xml"); String dirPath = dir+""; Document dom = UtilsForXML.getDocument(dirPath); Element root = dom.getRootElement(); ClientLoginUser person = new ClientLoginUser(); Element beQuery = (Element)root.selectSingleNode("//person[@id="+id+"]"); if(beQuery!=null){ person.setPublisherName(beQuery.elementText("publishername")); person.setServerUrl(beQuery.elementText("serverurl")); person.setUserName(beQuery.elementText("username")); person.setPassword(beQuery.elementText("password")); person.setId(id); } return person; } /* * 增加xml数据 * */ public static int AddClinetLoginUser(String appDir,String publisherName,String serverUrl,String userName,String passWord) throws Exception{ File dir = new File(appDir+"\\persons.xml"); if (!dir.exists()) { dir.createNewFile(); } int id = 1; String dirPath = dir+""; Document dom = UtilsForXML.getDocument(dirPath); Element root = dom.getRootElement(); List
list = root.elements("person"); if(!list.isEmpty()||list.size()!=0){ int count = list.size(); Element lastperson = list.get(count-1); String value = lastperson.attributeValue("id"); id = Integer.parseInt(value)+1; } // int id = (int) ((Math.random()*9+1)*1000); Element newPerson = root.addElement("person"); newPerson.addAttribute("id", id+""); Element publishername = newPerson.addElement("publishername"); publishername.setText(publisherName); Element serverurl = newPerson.addElement("serverurl"); serverurl.setText(serverUrl); Element username = newPerson.addElement("username"); username.setText(userName); Element password = newPerson.addElement("password"); password.setText(passWord); UtilsForXML.writeToXML(dom, dirPath); return id; } /* * 根据person属性id修改xml数据 * */ public static int UpdateClinetLoginUser(int id,String appDir,String publisherName,String serverUrl,String userName,String passWord) throws Exception{ File dir = new File(appDir+"\\persons.xml"); String dirPath = dir+""; Document dom = UtilsForXML.getDocument(dirPath); Element root = dom.getRootElement(); Element beQuery = (Element)root.selectSingleNode("//person[@id="+id+"]"); beQuery.element("publishername").setText(publisherName); beQuery.element("serverurl").setText(serverUrl); beQuery.element("username").setText(userName); beQuery.element("password").setText(passWord); UtilsForXML.writeToXML(dom, dirPath); return id; } /* * 根据person属性id删除xml数据 * */ public static int DeleteClinetLoginUser(int id,String appDir) throws Exception{ File dir = new File(appDir+"\\persons.xml"); String dirPath = dir+""; Document dom = UtilsForXML.getDocument(dirPath); Element root = dom.getRootElement(); Element beQuery = (Element)root.selectSingleNode("//person[@id="+id+"]"); beQuery.getParent().remove(beQuery); UtilsForXML.writeToXML(dom, dirPath); return id; }}

需要的工具类:

package com.founder.mrp.util;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.Reader;import org.dom4j.Document;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class UtilsForXML {    /**     * 需要一个方法来创建DOM4j的XML解析器并返回一个document对象     * add by hanwl     * @throws Exception      */    public static Document getDocument(String xmlPath) throws Exception {        Reader reader = new InputStreamReader(new FileInputStream(new File(xmlPath)),"utf-8");        SAXReader saxReader = new SAXReader();        //将XML文件路径传给Document对象并返回其实例dom        Document dom = saxReader.read(reader);        return dom;    }        /**     * 需要一个方法来将更新后的document对象写入到XML文件中去     * add by hanwl     * @throws Exception      */    public static void writeToXML(Document dom ,String xmlPath) throws Exception{                //首先创建样式和输出流        OutputFormat format = new OutputFormat().createPrettyPrint();        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(xmlPath),"utf-8");        //OutputStream out = new FileOutputStream(xmlPath);        XMLWriter writer = new XMLWriter(out,format);                //写入之后关闭流        writer.write(dom);        writer.close();    }}

用到的实体类:

package com.founder.mrp.domain;public class ClientLoginUser {    private int id;    private String publisherName;    private String serverUrl;    private String userName;    private String password;        public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getPublisherName() {        return publisherName;    }    public void setPublisherName(String publisherName) {        this.publisherName = publisherName;    }        public String getServerUrl() {        return serverUrl;    }    public void setServerUrl(String serverUrl) {        this.serverUrl = serverUrl;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }   }

这是web程序操作的代码,一些controller请求和jsp页面没有放,主要看dom4j操作xml

下面是本次用例XML文件:

测试3
http://loalhost
test3
123456
测试4
http://localhost
test4
123456

 

转载于:https://www.cnblogs.com/loong-hon/p/10002047.html

你可能感兴趣的文章
vue-cli3 中console.log报错
查看>>
GridView 中Item项居中显示
查看>>
UML类图五种关系与代码的对应关系
查看>>
如何理解作用域
查看>>
从无到满意offer,你需要知道的那些事
查看>>
P1516 青蛙的约会 洛谷
查看>>
SDOI2011 染色
查看>>
JQuery EasyUI combobox动态添加option
查看>>
面向连接的TCP概述
查看>>
前端快捷方式 [记录]
查看>>
亲测可用,解决端口被占用的指令!!
查看>>
MySQL--视图、触发器、事务、存储过程、内置函数、流程控制、索引
查看>>
Django--数据库查询操作
查看>>
自定义配置文件的使用
查看>>
js-20170609-运算符
查看>>
算法笔记_065:分治法求逆序对(Java)
查看>>
MSP430FLASH小结
查看>>
STM32 ADC转换时间
查看>>
结合实际业务场景聊一聊MVP模式的应用
查看>>
WinPE启动U盘的制作方法与软件下载(通用PE工具箱/老毛桃/大白菜WinPE)(转载)...
查看>>