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

我们知道XML文件既可以用来进行数据的传输,也可以配合DTD约束文件用来作为配置文件,当然其本质就是一个加了标签以及众多空格保持格式的字符串,那么就可以用Java进行操作。

本例是使用MyEclipse带入DOM4j解析时要用的jar包的基础上做的;当然DOM4j相对于DOM SAX 等解析方式的方便程度是不言而喻的。

下面是本次用例XML文件

小明

mail

185

Tom

Running

mail

185

Lily

这里我们用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 list = root.elements();

Element element = list.get(0);

for(Iterator 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 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();

Listlist = 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();

ListselectNodes = 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 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 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 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 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对象并返回其实例dom

Document 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文件不只是一种数据格式,更是一种应用场景

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值