其他分享
首页 > 其他分享> > 使用Dom4J的CRUD操做

使用Dom4J的CRUD操做

作者:互联网

PS:最近在学习xml使用Dom4j的小练习总结CRUD操做

首先,XML的特点之一就是可以存储数据,所以在这里我把xml就当作是数据库来理解。

首先先创建一个Students的类用于查询遍历操作

Students类

package com.wei.dom4j;

public class Students {
	private String id;
	private String name;
	private int age;
	private String sex;

	public Students(String id, String name, int age, String sex) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	public Students() {
		super();
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Students [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
}

保存XML文件的类

package com.wei.dom4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class SaveXML {
	public static void save(File file,Document document) {
		FileOutputStream fos = null;
		XMLWriter writer = null;
		try {
			// format.setIndentSize(2); // 行缩进
			// format.setNewlines(true); // 一个结点为一行
			// format.setTrimText(true); // 去重空格
			// format.setPadText(true);
			// format.setNewLineAfterDeclaration(false); // 放置xml文件中第二行为空白行

			fos = new FileOutputStream(file);
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			writer = new XMLWriter(fos, format);
			writer.write(document);
			System.out.println("使用dom4j操做xml成功,请注意查验!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally { // 关闭流
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

创建XML文件的类

package com.wei.dom4j;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


/**
 * @版权 : Copyright (c) 2021-2025 鼎立公司技术开发部
 * @author: WYP
 * @版本: 1.0
 * @创建日期: 2022年1月14日 上午9:21:44
 * @ClassName CreateXML
 * @类描述-Description: TODO(这里用一句话描述这个方法的作用)
 */
public class CreateXML {
	public static void main(String[] args) {
		//测试
		create(new File("resources/dom4jCreate.xml"));
	}

	public static void create(File file) {
		Document document = DocumentHelper.createDocument();
		// 创建根
		Element root = document.addElement("Students");
		root.addAttribute("info", "学生信息");
		// 第一个节点
		Element student1 = root.addElement("student");
		student1.addAttribute("id", "s001");
		Element name1 = student1.addElement("name");
		name1.addText("张三");
		Element age1 = student1.addElement("age");
		age1.addText("23");
		Element sex1 = student1.addElement("sex");
		sex1.addText("男");
		// 第二个节点
		Element student2 = root.addElement("student");
		student2.addAttribute("id", "s002");
		Element name2 = student2.addElement("name");
		name2.addText("李四");
		Element age2 = student2.addElement("age");
		age2.addText("21");
		Element sex2 = student2.addElement("sex");
		sex2.addText("女");
		//保存调用方法
		SaveXML.save(file, document);
	}
}

添加节点操做的类

package com.wei.dom4j;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class AddXML {
	public static void main(String[] args) {
		add(new File("resources/dom4jCreate.xml"));
	}

	public static void add(File file) {
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(file);
			Element root = document.getRootElement();
			Element student3 = root.addElement("student");
			student3.addAttribute("id", "s003");
			Element name3 = student3.addElement("name");
			name3.setText("张老刘");
			Element age3 = student3.addElement("age");
			age3.setText("25");
			Element sex3 = student3.addElement("sex");
			sex3.setText("男");

			SaveXML.save(file, document);
			System.out.println("使用dom4j添加xml节点成功,请注意查验!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

删除节点操作的类

package com.wei.dom4j;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class DeleteXML {

	public static void main(String[] args) {
		delete(new File("resources/dom4jCreate.xml"), "s003");
	}

	public static void delete(File file, String targetId) {
		try {
			SAXReader reader = new SAXReader();
			Document document = reader.read(file);
			Element root = document.getRootElement();
			// id类型的id这样查找
			// document.selectSingleNode("Students/student[@id='1003']");
			// String类型的id这样查找
			Node node = document.selectSingleNode("Students/student[@id='" + targetId + "']");
			if (node != null) {
				Element ele = (Element) node;
				root.remove(ele);
			} else {
				System.out.println("查无此人!");
			}
			SaveXML.save(file, document);
			System.out.println("删除成功!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

修改节点操作的类

package com.wei.dom4j;

import java.io.File;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class UpdateXML {
	public static void main(String[] args) {
		updateName(new File("resources/dom4jCreate.xml"), "s002","李老头");
	}
	
	public static void updateName(File file,String targetId,String updateName) {
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(file);
			Element root = document.getRootElement();
	
			List<Element> namelist = root.elements("student");
			for (Element element : namelist) {
				Attribute attr = element.attribute("id");
				if (attr.getText().equals(targetId)) {
					element.element("name").setText(updateName);
				}
			}
			SaveXML.save(file, document);
			System.out.println("修改成功!请注意查验!");
		} catch (Exception e) {
			System.err.println("修改失败!");
		}
	}
}

查询操做的类

package com.wei.dom4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class SelectXML {
	public static void main(String[] args) {
		selectByName(new File("resources/dom4jCreate.xml"));
		selectByFirstName(new File("resources/dom4jCreate.xml"));
		findAll(new File("resources/dom4jCreate.xml"));
	}

	/**
	 * 
	 * @Title: selectByName
	 * @Description:根据名字查询
	 * @return void  返回类型
	 */
	public static void selectByName(File file) {
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(file);
			Node node = document.selectSingleNode("Students/student[name='张三']");
			if (node != null) {
				Element e = (Element) node;
				System.out.println(e.attributeValue("id"));
				System.out.println(e.elementText("name"));
				System.out.println(e.elementText("age"));
				System.out.println(e.elementText("sex"));
			} else {
				System.out.println("查无此人");
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: selectByFirstName
	 * @Description: 根据名字模糊查询
	 * @return void  返回类型
	 */
	public static void selectByFirstName(File file) {
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(file);
			List<Element> list = document.selectNodes("Students/student[contains(name,'张')]");
			if (list.size() > 0) {
				for (Element element : list) {
					System.out.println(element.attributeValue("id"));
					System.out.println(element.elementText("name"));
					System.out.println(element.elementText("age"));
					System.out.println(element.elementText("sex"));
				}
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: findAll
	 * @Description: 查询所有的方法
	 * @return void  返回类型
	 */
	public static void findAll(File file) {
		SAXReader reader = new SAXReader();
		List<Students> Studntlist = new ArrayList<Students>();
		try {
			Document document = reader.read(file);
			Element rootElement = document.getRootElement();
			List<Node> list = rootElement.elements();
			if (list.size() > 0) {
				for (Node node : list) {
					Element e = (Element) node;
					String id = e.attributeValue("id");
					String name = e.elementText("name");
					String age = e.elementText("age");
					String sex = e.elementText("sex");
					
					Students students  = new Students(id,name,Integer.parseInt(age),sex);
					Studntlist.add(students);
				}
			}
			
			for(int i = 0;i<Studntlist.size();i++) {
				System.out.println(Studntlist.get(i));
			}
				
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

PS:查询的操做我是参考https://blog.csdn.net/weixin_37703598/article/details/103122376

创建XML运行结果

<?xml version="1.0" encoding="UTF-8"?>

<Students info="学生信息"> 
  <student id="s001"> 
    <name>张三</name>  
    <age>23</age>  
    <sex>男</sex> 
  </student>  
  <student id="s002"> 
    <name>李四</name>  
    <age>21</age>  
    <sex>女</sex> 
  </student>  
</Students>

增加节点操做结果

<?xml version="1.0" encoding="UTF-8"?>

<Students info="学生信息"> 
  <student id="s001"> 
    <name>张三</name>  
    <age>23</age>  
    <sex>男</sex> 
  </student>  
  <student id="s002"> 
    <name>李四</name>  
    <age>21</age>  
    <sex>女</sex> 
  </student>  
  <student id="s003">
    <name>张老刘</name>
    <age>25</age>
    <sex>男</sex>
  </student>
</Students>

修改XML文件结果

<?xml version="1.0" encoding="UTF-8"?>

<Students info="学生信息"> 
  <student id="s001"> 
    <name>张三</name>  
    <age>23</age>  
    <sex>男</sex> 
  </student>  
  <student id="s002"> 
    <name>李老头</name>  
    <age>21</age>  
    <sex>女</sex> 
  </student>  
  <student id="s003"> 
    <name>张老刘</name>  
    <age>25</age>  
    <sex>男</sex> 
  </student> 
</Students>

查询操作结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

标签:String,dom4j,Dom4J,CRUD,Element,使用,id,import,public
来源: https://blog.csdn.net/mmklo/article/details/122491472