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. 【转载】DSP基础--定点小数运算

    在FPGA实现算法过程中,大多数情况是用占用资源较少,延迟较低的定点数代替浮点数参与运算.那么浮点与定点数之间的区别以及转换方式是怎么的?下边这篇博文详细说明了这一问题.虽然是针对DSP芯片的,但思想 ...

  2. dynalist 配额

    2018-8-29 dynalist 配额 提示有一个G的配额 就是使用的流量用光了.仅有1个G

  3. 【Teradata】使用arcmain进行不落地数据迁移(管道)

    1.备份脚本准备 //脚本bak_ds.arc .logon 192.168.253.222/sysdba,learning1510; archive data tables(DS) ,release ...

  4. 关于vue-router中点击浏览器前进后退地址栏路由变了但是页面没跳转

    情景: 在进行正常页面跳转操作后(页面A跳转到页面B),点击浏览器的左上角的‘后退’按钮,点击后,可以看到url地址已经发生了变化(url由页面B变为页面A),hash值也已经是上一页的路由,但是浏览 ...

  5. 【转】Android辅助功能AccessibilityService自动全选择文字粘贴模拟输入

    网上找了很久AccessibilityService全选文字的方法,一直没找到,自己研究了半天,分享出来. /** * 输入文本 */ public void inputText(List<St ...

  6. 012_call和apply区别

    一. function fn(a,b) { console.log(this); } fn.call(null,1,2); //call为参数方式 fn.apply(null,[1,2]); //ap ...

  7. 10-ajax技术简介

    一.ajax是什么?是网页中的异步刷新技术.其核心是js+xml二.执行过程1.js的核心对象XMLHttpRequest是一个具备像后台发送请求的一个对象2.XMLHttpRequest可以异步发送 ...

  8. leetcode 263. Ugly Number 、264. Ugly Number II 、313. Super Ugly Number 、204. Count Primes

    263. Ugly Number 注意:1.小于等于0都不属于丑数 2.while循环的判断不是num >= 0, 而是能被2 .3.5整除,即能被整除才去除这些数 class Solution ...

  9. Sklearn中的回归和分类算法

    一.sklearn中自带的回归算法 1. 算法 来自:https://my.oschina.net/kilosnow/blog/1619605 另外,skilearn中自带保存模型的方法,可以把训练完 ...

  10. ubuntu安装docker-ce

    Docker Community Edition (CE)/Docker社区版非常适合希望开始使用Docker并尝试使用基于容器的应用程序的开发人员和小型团队.Docker CE有2个版本:stabl ...