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文件进行增删改查操作的更多相关文章

  1. 使用dom4j对xml文件进行增删改查

    1.使用dom4j技术对dom_demo.xml进行增删改查 首选要下载dom4j的jar包 在官网上找不到,网上搜索了一下在这个链接:http://sourceforge.net/projects/ ...

  2. java对xml文件做增删改查------摘录

    java对xml文件做增删改查 package com.wss; import java.io.File;import java.util.ArrayList;import java.util.Lis ...

  3. Asp.Net 操作XML文件的增删改查 利用GridView

    不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了 index.aspx 文件 ...

  4. php对xml文件的增删改查

    源文件<?xml version="1.0" encoding="utf-8"?><root>  <endTime>2016 ...

  5. C# 本地xml文件进行增删改查

    项目添加XML文件:FaceXml.xml,并复制到输出目录 FaceXml.xml <?xml version="1.0" encoding="utf-8&quo ...

  6. java对xml文件做增删改查

    http://www.cnblogs.com/wangchenyang/archive/2011/08/23/2150530.html http://www.blogjava.net/weishuan ...

  7. dom4j解析xml文档(增删改查)

    package itcast.dom4j; import java.io.File; import java.io.FileOutputStream; import java.io.FileWrite ...

  8. xml 文件的增删改查

    序列化和反序列化helper using System; using System.Collections.Generic; using System.Linq; using System.Text; ...

  9. SpringBoot结合Mybatis 使用 mapper*.xml 进行数据库增删改查操作

    什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架. MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索. MyBa ...

随机推荐

  1. 【Python 10】汇率兑换3.0(while循环)

    1.案例描述 设计一个汇率换算程序,其功能是将美元换算成人民币,或者相反. 2.0增加功能:根据输入判断是人民币还是美元,进行相应的转换计算 3.0增加功能:程序可以一直运行,知道用户选择退出 2.案 ...

  2. Python开发【内置模块篇】

    动态导入模块 动态导入模块 导入一个库名为字符串的 module_t = __import__('m1.t') print (module_t) #m1 import importlib m=impo ...

  3. Spark RDD持久化、广播变量和累加器

    Spark RDD持久化 RDD持久化工作原理 Spark非常重要的一个功能特性就是可以将RDD持久化在内存中.当对RDD执行持久化操作时,每个节点都会将自己操作的RDD的partition持久化到内 ...

  4. ESP8266产品ID

    ESP.getChipId() https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/Chip ...

  5. PyInstaller Extractor安装和使用方法

    PyInstaller Extractor是可以提取出PyInstaller所创建的windows可执行文件的资源内容. 关于PyInstaller的介绍:PyInstaller安装使用方法 使用Py ...

  6. Java 最常见的 200+ 面试题汇总

    这份面试清单是我从 2015 年做 TeamLeader 之后开始收集的,一方面是给公司招聘用,另一方面是想用它来挖掘我在 Java 技术栈中的技术盲点,然后修复和完善它,以此来提高自己的技术水平.虽 ...

  7. 基于 HTML5 的 WebGL 楼宇自控 3D 可视化监控

    前言 智慧楼宇和人们的生活息息相关,楼宇智能化程度的提高,会极大程度的改善人们的生活品质,在当前工业互联网大背景下受到很大关注.目前智慧楼宇可视化监控的主要优点包括: 智慧化 -- 智慧楼宇是一个生态 ...

  8. Python Revisited Day 05(模块)

    目录 5.1 模块与包 5.1.1 包 5.2 Python 标准库概览 5.2.1 字符串处理 io.StringIO 类 5.2.3 命令行设计 5.2.4 数学与数字 5.2.5 时间与日期 5 ...

  9. MySQL源码包编译安装

    +++++++++++++++++++++++++++++++++++++++++++标题:MySQL数据库实力部署时间:2019年3月9日内容:MySQL源码包进行编译,然后部署MySQL单实例重点 ...

  10. vue入门之编译项目

    好记性不如烂笔头,最近又开始学习vue了,编译的过程中遇到几个小坑,特此一记.     首先说一下vue项目如何编译,其实很简单,cd到项目文件夹,然后执行命令: npm run bulid 不过np ...