基于Java的XML文件模拟数据库进行增删改查操作

news/2023/10/4 0:39:22
我们知道XML文件既可以用来进行数据的传输,也可以配合DTD约束文件用来作为配置文件,当然其本质就是一个加了标签以及众多空格保持格式的字符串,那么就可以用Java进行操作。本例是使用MyEclipse带入DOM4j解析时要用的jar包的基础上做的;当然DOM4j相对于DOM SAX 等解析方式的方便程度是不言而喻的。下面是本次用例XML文件<?xml version="1.0" encoding="UTF-8"?><persons> <person age="30" weight="80" gender="femail"> <name>小明</name>  <gender>mail</gender>  <hight>185</hight> </person>  <person age="21" weight="78"> <name>Tom</name>  <favorite nationality="China">Running</favorite>  <gender>mail</gender>  <hight>185</hight> </person>  <person age="21" weight="45"> <name>Lily</name> </person> 
</persons>

这里我们用Java进行XML文件操作,代码如下:

package test_XML;import java.util.Iterator;
import java.util.List;import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Entity;
import org.dom4j.Node;import utils.XMLUtils;public class myDemo1 {public static void main(String[] args) throws Exception{//以下方法均有说明,读者可自行选取//getFirstText();//getSecondText();//insertElement();//insertAttrAndEle();//deleteSubElement();//updateElement();//insertAttr();//updateAttr();//deleteAttr();//getAllNameNode();//getAllNameNode();//getSecondPersonAttr();//getRootNodeAttr();//getSecongElelmentAttr();}/*** 获取第二个人的所有属性值并输出到控制台上* @throws Exception*/private static void getSecongElelmentAttr() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();List<Element> list = root.elements();Element element = list.get(0);for(Iterator<Attribute> i = element.attributeIterator();i.hasNext();){Attribute next = i.next();//注意这边需要加入范型以确保是一个Attribute对象,然后调用其getValue()方法即可输出所需值System.out.println(next.getValue());}}/*** 查询所有人的年龄属性并遍历输出* @throws Exception*/private static void getRootNodeAttr() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();List<Element> list = root.elements();for(Iterator i = root.elementIterator("person");i.hasNext();){Element element = (Element)i.next();String attributeValue = element.attributeValue("age");System.out.println(attributeValue);}}	/*** 获取第二个人的性别元素并输出其内容* @throws Exception*/private static void getSecondPersonAttr() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();List<Element>list = root.elements();Element gender = list.get(1).element("gender");System.out.println(gender.getText());}/*** 获取所有person节点下的name子节点并遍历输出到控制台* @throws Exception*/private static void getAllNameNode() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();List<Element>selectNodes = root.selectNodes("//name");for ( Iterator i = root.elementIterator(); i.hasNext(); ) {Element element = (Element) i.next();System.out.println(element.element("name").getName());	 }}/*** 遍历输出所有person节点并输出到控制台上* @throws Exception*/private static void getAllPersonNode() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();List selectNodes = root.selectNodes("//name");for ( Iterator i = root.elementIterator(); i.hasNext(); ) {Element element = (Element) i.next();System.out.println(element.getName());	 }}/*** 获取第三个人的体重属性并删除* @throws Exception*/private static void deleteAttr() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();List<Element> list = root.elements();Element secondperson = list.get(1);Attribute attribute = secondperson.attribute("weight");if(attribute == null){System.out.println("False! Not exsit");}attribute.getParent().remove(attribute);		XMLUtils.writerToXML(dom, "persons.xml");System.out.println("~~~~~~~~~~Delete attribute successfully!~~~~~~~~~~~");}/*** 更新第一个人的年龄属性并输出更新前后的值到控制台* @throws Exception*/private static void updateAttr() throws Exception {Document dom =XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();Attribute age = root.element("person").attribute("age");System.out.println("before updating:"+age.getValue());age.setText("30");XMLUtils.writerToXML(dom, "persons.xml");System.out.println("behind updating:"+age.getValue());System.out.println("************Update successfully!***********");}/*** 给第一个人添加一个属性gender 值为femail* @throws Exception*/private static void insertAttr() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();root.element("person").addAttribute("gender", "femail");XMLUtils.writerToXML(dom, "persons.xml");System.out.println("+++++++++Add attribute successfully!++++++++");}/*** 获取第一个人的姓名标签并修改* @throws Exception*/private static void updateElement() throws Exception {Document dom =XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();//1.获取第一个人2.更改其name属性的值Element firstPerson = root.element("person");firstPerson.element("name").setText("WXM!!!!");//切记分清楚那个是root标签那个是需要修改的标签XMLUtils.writerToXML(dom, "persons.xml");System.out.println("=========Update successfully!============");}/*** 删除第三个人的gender标签* @throws Exception*/private static void deleteSubElement() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();//1.获取第三个人  2.获取第三个人的gender节点 并删除List<Element> list = root.elements();Element gender = list.get(2).element("gender");gender.getParent().remove(gender);//只能通过父标签来删除XMLUtils.writerToXML(dom, "persons.xml");System.out.println("=======Delete successfully=======");}/*** 给第二个人的身高元素前面插入一个爱好元素并为这个属性加入一个国籍属性* @throws Exception*/private static void insertAttrAndEle() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();//1.创建一个爱好节点 2.获取第二本书并将安好节点插到其身高节点的前面Element favorite = DocumentHelper.createElement("favorite").addAttribute("nationality", "China");favorite.setText("Running");List<Element> listPersons = root.elements();Element person = (Element)listPersons.get(1);List listPerson = person.elements();listPerson.add(1,favorite );XMLUtils.writerToXML(dom, "persons.xml");System.out.println("=========Insert sucessfully!========");}/*** 给第一个人添加一个身高节点* @throws Exception*/private static void insertElement() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();//1.创建一个节点  2.获取第一个人 并将创建的节点挂载到第一个人上Element hight = DocumentHelper.createElement("hight");hight.setText("185");root.element("person").add(hight);XMLUtils.writerToXML(dom, "persons.xml");System.out.println("=========Add successfully=========");}/*** 查询第二个人的性别,并输出到控制台* @throws Exception*/private static void getSecondText() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();List<Element> list = root.elements();Element secondElement = list.get(1).element("gender");System.out.println(secondElement.getText());}/*** 获取第一个人的姓名属性并将之打印到控制台* @throws Exception*/private static void getFirstText() throws Exception {Document dom = XMLUtils.getDocument("persons.xml");Element root = dom.getRootElement();Element person = root.element("person").element("name");System.out.println(person.getTextTrim());}
}//当然每次都要新建一个DOM4j的XML文件解析器,我们可以抽出来做一个工具类然后使用就能方便一下  代码如下:package com.buu;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;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对象*/public static Document getDocument(String xmlPath) throws Exception {SAXReader reader = new SAXReader();//将XML文件路径传给Document对象并返回其实例domDocument dom = reader.read(new File(xmlPath));return dom;}/*** 需要一个方法来将更新后的document对象写入到XML文件中去* @throws Exception */public static void writeToXML(Document dom ,String xmlPath) throws Exception{//首先创建样式和输出流OutputFormat format = new OutputFormat().createPrettyPrint();OutputStream out = new FileOutputStream(xmlPath);XMLWriter writer = new XMLWriter(out,format);//写入之后关闭流writer.write(dom);writer.close();}
}//上面是使用DOM4j解析方式操作XML文件的一些方法,等这些方法我们掌握之后就可以用XML文件模//拟数据库进行数据的增删改查操作了  具体代码如下:package com.buu;import java.util.Scanner;import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;public class Manager {public static void main(String[] args) throws Exception{//1.接受用户输入信息//2.获取用户输入的信息//3.判断并处理请求while(true){System.out.println("Please Input your choice!");System.out.println("1.add      2.query     3.delete");Scanner input = new Scanner(System.in);String type = input.nextLine();if("1".equals(type)){Person person = new Person();//将输入信息保存到person对象中System.out.println("Please input your name:");String name = input.nextLine();person.setName(name);System.out.println("Please input your gender:");String gender = input.nextLine();person.setGender(gender);System.out.println("Please input your age:");String age = input.nextLine();person.setAge(age);System.out.println("Please input your weight:");String weight = input.nextLine();person.setWeight(weight);add(person);System.out.println("=========Add successfully!==========");}else if("2".equals(type)){System.out.println("Please input age:");String age = input.nextLine();if(age==null){return;}String queryPerson = query(age);System.out.println("***"+queryPerson+"***");System.out.println();}else if("3".equals(type)){System.out.println("Please input weight");String weight = input.nextLine();if(weight==null){System.out.println("Please input again!");}delete(weight);System.out.println("''''''''Delete successfully''''''''");}else{System.out.println(" False! Please check !");}}}private static void delete(String weight) throws Exception {Document dom = UtilsForXML.getDocument("Persons.xml");Element root = dom.getRootElement();Element beDelete = (Element)root.selectSingleNode("//person[@weight="+weight+"]");if(beDelete == null){System.out.println("Not exist!");}beDelete.getParent().remove(beDelete);UtilsForXML.writeToXML(dom, "Persons.xml");}private static String query(String age) throws Exception {Document dom = UtilsForXML.getDocument("Persons.xml");Element root = dom.getRootElement();Element beQuery = (Element)root.selectSingleNode("//person[@age="+age+"]");if(beQuery == null){System.out.println("Not exist!");}Person person = new Person();person.setName(beQuery.elementText("name"));person.setWeight(beQuery.attributeValue("weight"));person.setAge(beQuery.attributeValue("age"));person.setGender(beQuery.elementText("gender"));return person.toString();}private static void add(Person person) throws Exception {Document dom = UtilsForXML.getDocument("Persons.xml");Element root = dom.getRootElement();//注意这边只是获取根元素但其下面没有任何元素,需要手动添加Element personElement = root.addElement("person").addAttribute("age", person.getAge()).addAttribute("weight", person.getWeight());personElement.addElement("name").setText(person.getName());personElement.addElement("gender").setText(person.getGender());//将更新后的document对象写入到XML文件中去UtilsForXML.writeToXML(dom, "Persons.xml");}
}//总结:XML文件不只是一种数据格式,更是一种应用场景

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.yaotu.net/news/605401.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

PHP开发支付宝之网站支付--流程简介

前言 前端时间自己开发了一个drupal的支付宝模块&#xff0c;现在整理一下过程&#xff0c;因为支付宝官方网站提供的接口及文档都是新接口的&#xff0c;而且使用新接口的过程比较麻烦一点&#xff0c;所以整理一下 1.支付宝的账号必须经过企业资格的审核才可以进行正式环境的…

cache详解

什么是缓存&#xff1f; Web 应用程序通常都是被多个用户访问。一个Web站点可能存在一个“重量级”的加载&#xff0c;它能够使得站点在访问的时候&#xff0c;拖慢整个服务器。当站点被大量用户同时访问的时候&#xff0c;访问速度缓慢是大部分网站共同存在的问题。为了解决这…

(五)nginx如何调用php和php-fpm的作用和工作原理

nginx如何调用php 采用nginxphp作为webserver的架构模式&#xff0c;在现如今运用相当广泛。然而第一步需要实现的是如何让nginx正确的调用php。由于nginx调用php并不是如同调用一个静态文件那么直接简单&#xff0c;是需要动态执行php脚本。所以涉及到了对nginx.conf文件的配置…

GC算法详解

本文主要内容&#xff1a; GC的概念GC算法引用计数法&#xff08;无法解决循环引用的问题&#xff0c;不被java采纳&#xff09; 根搜索算法 现代虚拟机中的垃圾搜集算法&#xff1a; 标记-清除 复制算法&#xff08;新生代&#xff09; 标记-压缩&#xff08;老年代&#xff…

php 读取功能分割大文件实例详解

在php中&#xff0c;对于文件的读取时&#xff0c;最快捷的方式莫过于使用一些诸如file、file_get_contents之类的函数。 但当所操作的文件是一个比较大的文件时&#xff0c;这些函数可能就显的力不从心, 下面将从一个需求入手来说明对于读取大文件时&#xff0c;常用的操作方法…

Beanstalk分布式内存队列系统

Beanstalk是一个高性能、轻量级的、分布式的、内存型的消息队列系统。最初设计的目的是想通过后台异步执行耗时的任务来降低高容量Web应用系统的页面访问延迟。其实Beanstalkd是典型的类Memcached设计&#xff0c;协议和使用方式都是同样的风格。其基本设计思想很简单&#xff…

一个请求过来都经过了什么

面试的时候特别喜欢问一个问题&#xff1a;”请描述一下一个请求过来到响应完成都做了什么&#xff0c;越详细越好。” 对于一个高手来说&#xff0c;他只要回答好了这一个问题&#xff0c;技术面试就通过了。一般把这个问题的答案压缩到40分钟到1个小时。因为一般的技术面试都…

XDebug调试

本文介绍如何使用PhpStorm集成xdebug在本地开发环境进行断点调试的技巧。 我配置的环境是&#xff1a;Windows10 PhpStorm PHP5.6。 1. 下载xdebug的扩展&#xff0c;并配置到php.ini View code 第一行是加载xdebug的扩展&#xff0c;路径需根据自己的环境修改。 第二行是…

Mock方法介绍

1.现有的单元测试框架 单元测试是保证程序正确性的一种有效的测试手段&#xff0c;对于不同的开发语言&#xff0c;通常都能找到相应的单元框架。 借助于这些单测框架的帮助&#xff0c;能够使得我们编写单元测试用例的过程变得便捷而优雅。框架帮我们提供了case的管理&#xf…

sed入门详解教程

sed 是一个比较古老的&#xff0c;功能十分强大的用于文本处理的流编辑器&#xff0c;加上正则表达式的支持&#xff0c;可以进行大量的复杂的文本编辑操作。sed 本身是一个非常复杂的工具&#xff0c;有专门的书籍讲解 sed 的具体用法&#xff0c;但是个人觉得没有必要去学习它…

MySQL索引原理及慢查询优化【来源美团】

背景 MySQL凭借着出色的性能、低廉的成本、丰富的资源&#xff0c;已经成为绝大多数互联网公司的首选关系型数据库。虽然性能出色&#xff0c;但所谓“好马配好鞍”&#xff0c;如何能够更好的使用它&#xff0c;已经成为开发工程师的必修课&#xff0c;我们经常会从职位描述上…

MySQL慢查询优化、索引优化、以及表等优化总结

MySQL优化概述 MySQL数据库常见的两个瓶颈是&#xff1a;CPU和I/O的瓶颈。 CPU在饱和的时候一般发生在数据装入内存或从磁盘上读取数据时候。 磁盘I/O瓶颈发生在装入数据远大于内存容量的时候&#xff0c;如果应用分布在网络上&#xff0c;那么查询量相当大的时候那么平瓶颈…

转载kafka集群搭建

原文地址&#xff1a;https://www.dqzboy.com/kafka%E9%9B%86%E7%BE%A4%E5%AE%89%E8%A3%85%E9%83%A8%E7%BD%B2%E5%92%8C%E5%AE%9E%E8%B7%B5 一、kafka介绍 1、什么是消息队列 消息队列技术是分布式应用间交换信息的一种技术。消息队列可驻留在内存或磁盘上, 队列存储消息直到…

力扣2:两数相加

题目&#xff1a; 给你两个 非空 的链表&#xff0c;表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的&#xff0c;并且每个节点只能存储 一位 数字。 请你将两个数相加&#xff0c;并以相同形式返回一个表示和的链表。 你可以假设除了数字 0 之外&#xff0c;这…

力扣5:最长回文子串

给你一个字符串 s&#xff0c;找到 s 中最长的回文子串。 示例 1&#xff1a; 输入&#xff1a;s "babad" 输出&#xff1a;"bab" 解释&#xff1a;"aba" 同样是符合题意的答案。 1.中心扩散法 //中心扩散法 func longestPalindrome(s stri…

etcd常见错误及解决

1."etcdserver: mvcc: database space exceeded"错误 只要你使用过 etcd 或者 Kubernetes&#xff0c;大概率见过这个错误。它是指当前 etcd db 文件大小超过了配额&#xff0c;当出现此错误后&#xff0c;你的整个集群将不可写入&#xff0c;只读&#xff0c;对业务…

golang windows64位操作系统上编译32位应用

golang windows64位操作系统上编译32位应用 将GOARCHamd64改为386 改后程序中调用sqlite会报错 Binary was compiled with CGO_ENABLED0, go-sqlite3 requires cgo to work. This is a stub 所以还需要将CGO_ENABLED设置为1

linux系统很卡的基本排查方法

1. 查看内存使用情况 free -g 当观察到free栏已为0的时候&#xff0c;表示内存基本被吃完了&#xff0c;那就释放内存吧&#xff08;释放内存参考上篇文章&#xff09; 2. 查看磁盘使用情况 df -h 当发现磁盘使用率很高时&#xff0c;那就要释放磁盘空间了&#xff0c;删除一些…

监控报警产品对比

Prometheus架构图&#xff1a;
最新文章