使用dom4j实现xml的增查删改

来源:互联网 发布:交大医学院网络英语 编辑:程序博客网 时间:2024/06/10 06:12

dom4j是一款开放源码的用于解析xml的java api,这里给大家提供一个免费的dom4j 1.6.1的地址  :http://download.csdn.net/download/u010426133/7763815

下面给大家介绍一下xml的具体用法:

1.读取解析xml文档
//读取一个xml文档并返回一个document用于操作 public Document getDocument(String fileName) {SAXReader reader = new SAXReader(); Document document = null;try {document = reader.read(new File(fileName));} catch (DocumentException e) {e.printStackTrace();}return document;}

2.读取根节点
Element root = document.getRootElement(); //获取根节点
3.向一个节点中插入元素或属性;
Element root = document.getRootElement();// 取根节点Element student = root.addElement("student"); // 添加一个studnet元素student.addAttribute("id", "1000");   //在student元素中添加一个id属性student.addElement("name").addText("张三"); //在student元素中添加一个子元素并赋值;student.addElement("sex").addText("男");student.addElement("birthday").addText("1993-07-15");
4.用xpath查找xml中指定的节点,如:
List<Element> list = document.selectNodes("//student");
这是查找xml文档中含有student的所有节点,下面我也给大家介绍一下xpath的常用语法,一些不常用的语法我不做介绍:

  • //students/student表示搜索students元素下的所有student元素
  • //student表示搜索xml文档中所有student元素
  • //student/* 表示xml文档中student的所有子元素
  • /students/student[1] 表示students元素下的第一个student元素
  • /students/student[age] 表示students元素下含有age子元素的所有studnet
  • /students/student[age=20] 在上面的基础上加了一个限制条件age=20;

  • //student[@id]表示含有属性id的所有studnet元素

以上这些语法在xml解析中基本上够用了,如果想深入了解xpath的用法,可以到xpath学习: http://www.w3school.com.cn/xpath/index.asp

5.将document写入xml

public static boolean saveToXml(Document document,String fileName){OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8");try {XMLWriter writer = new XMLWriter(new FileOutputStream(fileName),format);writer.write(document);writer.close();} catch (UnsupportedEncodingException | FileNotFoundException e) {e.printStackTrace();return false;} catch (IOException e) {e.printStackTrace();return false;}return true;}

以上这么多足以写一个用xml存储数据的小型管理系统,我这里给大家实现了一个学生信息的管理系统,具体的前台没有帮大家写,只写了entity层、dao层、业务逻辑层。

代码我已经上传到网上,大家可以下载查看:http://git.oschina.net/chengxianhu/mycode

0 0
原创粉丝点击