博客
关于我
使用Java操作xml文档
阅读量:514 次
发布时间:2019-03-07

本文共 5594 字,大约阅读时间需要 18 分钟。

使用Java操作xml文档

DOM文档对象模型

DOM(Document Object Model)定义了访问和操作XML文档的标准方法。DOM将XML文档转化为树状结构,通过DOM树可以完成对文档中的所有元素的读写操作。

DOM结构概述

在DOM模型中,XML文档被解析为一个Document对象,Document对象下包含多个Element对象。每个Element对象又可能包含子Element对象、Attribute对象或是Text内容。

Dom4j

Dom4j是一个功能强大且易于使用的开源库,专为解析XML设计。它在性能、功能和可用性上具有显著优势。

Dom4j安装和配置

Dom4j可以通过百度搜索找到官方文档地址及安装教程。安装完成后,只需依次使用SAXReader解析XML文件即可。

读取Xml数据

依次使用Dom4j读取并解析XML文件

package com.example;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;public class XmlReader {    public void readXml(String filePath) {        try {            SAXReader reader = new SAXReader();            Document document = reader.read(filePath);            Element root = document.getRootElement();                        // 获取所有"employee"节点            List
employees = root.elements("employee"); for (Element employee : employees) { // 获取employee节点的属性 System.out.println("员工编号:" + employee.attribute("no").getText()); // 获取名称 System.out.println("员工姓名:" + employee.element("name").getText()); // 获取年龄 System.out.println("年龄:" + employee.element("age").getText()); // 获取薪资 System.out.println("薪资:" + employee.element("salary").getText()); // 获取部门信息 Element department = employee.element("department"); System.out.println("部门名称:" + department.element("dname").getText()); System.out.println("部门地址:" + department.element("address").getText()); System.out.println("#################################"); } } catch (DocumentException e) { e.printStackTrace(); } } public static void main(String[] args) { XmlReader reader = new XmlReader(); reader.readXml("hr.xml"); }}

写入Xml数据

通过Dom4j写入XML文件,具体操作如下:

package com.example;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXWriter;public class XmlWriter {    public void writeXml(String filePath) {        try {            // 解决File读取流程问题            SAXWriter writer = new SAXWriter(new java.io.FileOutputStream(filePath, false), "UTF-8");            Document document = writer.read(new java.io.File("hr.xml"));            Element root = document.getRootElement();            // 创建新员工节点            Element newEmployee = root.addElement("employee");            newEmployee.setAttribute("no", "4233");            // 添加员工信息            newEmployee.addElement("name").setText("x3");                        // 添加年龄            newEmployee.addElement("age").setText("22");                        // 添加薪资            newEmployee.addElement("salary").setText("3622");                        // 添加部门信息            Element department = newEmployee.addElement("department");            department.addElement("dname").setText("会计部");            department.addElement("address").setText("XX大厦-B102");            // 写入文件            writer.write(document);            writer.close();        } catch (Exception e) {            e.printStackTrace();        }    }    public static void main(String[] args) {        XmlWriter writer = new XmlWriter();        writer.writeXml("hr.xml");    }}

XPath路径表达式

XPath是用于查询和操作XML数据的强大工具。掌握XPath可以极大简化XML数据提取操作。

XPath基础知识

  • 元素选择xpath表达式用于选取文档中指定节点的元素。例如,/hr/employee表示选取hr下直接子元素employee。

  • 属性选择:使用@符号可以获取元素属性。例如,//employee[@no='3309']表示选取no属性为3309的所有employee节点。

  • 节点选择:通用节点选择用*,而具体选择用elementName。例如,//employee表示选取所有employee节点,而*/employee表示选取所有注意下的employee节点。

XPath案例分析

以下是几个常见的XPath表达式示例:

  • 选取所有书店的书籍//bookstore/book

  • 选取拥有特定属性的节点//employee[@no='4233']

  • 选取特定位置的节点/bookstore/book[2]

  • 复合选择//employee[name='x1'] | //employee[name='x2']

XPath代码示例

以下是使用Dom4j进行XPath查询的代码示例:

package com.example;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.Node;import org.dom4j.io.SAXReader;public class XPathTest {    public void xpathTest(String xpathExp) {        try {            SAXReader reader = new SAXReader();            Document document = reader.read(new java.io.File("hr.xml"));                        List
nodes = document.selectNodes(xpathExp); for (Node node : nodes) { Element emp = (Element) node; System.out.println("员工编号:" + emp.attributeValue("no")); System.out.println("员工姓名:" + emp.elementText("name")); System.out.println("员工年龄:" + emp.elementText("age")); System.out.println("员工薪资:" + emp.elementText("salary")); System.out.println("员工部门名称:" + emp.element("department").elementText("dname")); System.out.println("员工部门地址:" + emp.element("department").elementText("address")); System.out.println("#################################"); } } catch (DocumentException e) { e.printStackTrace(); } } public static void main(String[] args) { XPathTest test = new XPathTest(); // 测试多个xpath表达式 test.xpath("/hr/employee"); test.xpath("//employee"); test.xpath("//employee[salary<4000]"); test.xpath("//employee[name='x1']"); test.xpath("//employee[@no='3309']"); test.xpath("//employee[1]"); test.xpath("//employee[last()]"); test.xpath("//employee[position()<6]"); test.xpath("//employee[3] | //employee[1]"); }}

希望以上内容能帮助您更好地理解和使用Java操作XML文档。

转载地址:http://chijz.baihongyu.com/

你可能感兴趣的文章
python语言有哪些优点和缺点_Python有哪些优缺点,你了解吗?
查看>>
Python 从入门到精通:30天速成教程到底有多狠?你能坚持下来吗?
查看>>
Python 从数据库中存储和检索密码的最安全方法
查看>>
Python语言及其应用 - 知识点遍历
查看>>
Python 优化提速的 8 个小技巧
查看>>
Python 余弦相似度与皮尔逊相关系数 计算
查看>>
python 使用execjs 报编码错误解决办法,UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 145: il
查看>>
python 使用filetype校验文件
查看>>
Python 使用flush函数将缓冲区数据立即写磁盘
查看>>
python 使用in判断不准确,in不好使
查看>>
Python 使用pandas 进行查询和统计详解
查看>>
Redis 配置文件redis.conf详细解释
查看>>
python网络爬虫(2)——scrapy框架的基础使用
查看>>
python网络爬虫实例教程试读_Python网络爬虫实战教程(全套完整版) - 学途无忧网 - 做技术的王者 - Powered By EduSoho...
查看>>
Python 使用哈希函数用于加密
查看>>
Python 依赖管理的革新——Poetry 深度解析
查看>>
python 保留精度及增加去除数字的千位分隔符(金额化数字)
查看>>
python 倒计时 9,8,7,。。。。。。0
查看>>
Python 入门开发学习笔记之数据的增删改查
查看>>
Python 入门教程(2)搭建环境 2.4、VSCode配置Node.js运行环境
查看>>