Java使用DOM4J对XML文件进行增删改查操作
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<ClientLoginUser> 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<ClientLoginUser> persons = new ArrayList<ClientLoginUser>(); 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<Element> 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文件:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="1">
<publishername>测试3</publishername>
<serverurl>http://loalhost</serverurl>
<username>test3</username>
<password>123456</password>
</person>
<person id="2">
<publishername>测试4</publishername>
<serverurl>http://localhost</serverurl>
<username>test4</username>
<password>123456</password>
</person>
</persons>
Java使用DOM4J对XML文件进行增删改查操作的更多相关文章
- 使用dom4j对xml文件进行增删改查
		
1.使用dom4j技术对dom_demo.xml进行增删改查 首选要下载dom4j的jar包 在官网上找不到,网上搜索了一下在这个链接:http://sourceforge.net/projects/ ...
 - java对xml文件做增删改查------摘录
		
java对xml文件做增删改查 package com.wss; import java.io.File;import java.util.ArrayList;import java.util.Lis ...
 - Asp.Net 操作XML文件的增删改查 利用GridView
		
不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了 index.aspx 文件 ...
 - php对xml文件的增删改查
		
源文件<?xml version="1.0" encoding="utf-8"?><root> <endTime>2016 ...
 - C# 本地xml文件进行增删改查
		
项目添加XML文件:FaceXml.xml,并复制到输出目录 FaceXml.xml <?xml version="1.0" encoding="utf-8&quo ...
 - java对xml文件做增删改查
		
http://www.cnblogs.com/wangchenyang/archive/2011/08/23/2150530.html http://www.blogjava.net/weishuan ...
 - dom4j解析xml文档(增删改查)
		
package itcast.dom4j; import java.io.File; import java.io.FileOutputStream; import java.io.FileWrite ...
 - xml 文件的增删改查
		
序列化和反序列化helper using System; using System.Collections.Generic; using System.Linq; using System.Text; ...
 - SpringBoot结合Mybatis 使用 mapper*.xml 进行数据库增删改查操作
		
什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架. MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索. MyBa ...
 
随机推荐
- spring boot 中使用 jpa以及jpa介绍
			
1.什么是jpa呢?JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中.12.jpa具有什么 ...
 - apache https配置【转】
			
博文来源:apache https配置 参考博文:apache.nginx配置自签名证书 1. 确认是否安装ssl模块 是否有mod_ssl.so文件 2. 生成证书和密钥 linux下 步骤1: ...
 - Scheme来实现八皇后问题(2)
			
版权申明:本文为博主窗户(Colin Cai)原创,欢迎转帖.如要转贴,必须注明原文网址 http://www.cnblogs.com/Colin-Cai/p/9790466.html 作者:窗户 Q ...
 - Jetson TX2(1)ubutu1604--安装Nvidia Linux驱动
			
https://www.jianshu.com/p/c8ebe4aaa708 系统开机首次进入的是以nvidia用户登录的Ubuntu 命令行界面.Nvidia 驱动安装 通过sudo su 输入密码 ...
 - IDEA+API && SPI
			
JAVA中API和SPI的区别:https://blog.csdn.net/quanaianzj/article/details/82500019
 - Web前端知识点记录
			
一.HTML的加载顺序 浏览器边下载HTML,边解析HTML代码,二者是从上往下同步进行的 先解析<head>中的代码,在<head>中遇到了<script>标签, ...
 - 使用Kernel NetEm和tc模拟复杂网络环境
			
关键词:netem(Network Emulator).tc(Traffic Control). 大部分局域网环境良好,但是产品实际网络环境可能千差万别,为了对产品进行各种情况测试就需要模拟网络环境. ...
 - 洛谷P4431
			
题意翻译 题目大意: 给定一个n∗m的矩阵,每次你可以选择前进一格或转弯(90度),求在不出这个矩阵的情况下遍历全部格点所需最少转弯次数.有多组数据 输入格式: 第一行一个整数k,表示数据组数 以下k ...
 - jenkins的安装部署
			
jenkins安装 参考连接: https://wiki.jenkins.io/display/JENKINS/Installing+Jenkins+on+Red+Hat+distributions ...
 - 关于childNodes的删除
			
在使用childNodes时,发现需要删除的元素多于1时,会出现无法全部删除的情况.谷歌以后发现,该属性返回的子节点集合是实时更新的,也就是说,在for循环中,当删除第一个子节点之后,第二次删除的是原 ...