当前位置: 首页 > article >正文

XML DOM4J 二、document对象

DOM4J获取Document对象:

使用DOM4J来加载XML文档,需要先获取SAXReader对象,然后通过SAXReader对象的read()方法来加载XML文档:

        SAXReader reader = new SAXReader();
//		reader.setValidation(true);
		Document doc = reader.read("src/students.xml");

DOM4J保存Document对象

保存Document对象需要使用XMLWriter对象的write()方法来完成,在创建XMLWriter时还可以为其指定XML文档的格式(缩进字符串以及是否换行),这需要使用OutputFormat来指定。

        doc.addDocType("students", "", "students.dtd");
		OutputFormat format = new OutputFormat("\t", true);
		format.setEncoding("UTF-8");
		XMLWriter writer = new XMLWriter(new FileWriter(xmlName), format);
		writer.write(doc);
		writer.close();

DOM4J创建Document对象:

DocumentHelper类有很多的createXXX()方法,用来创建各种Node对象。

Document doc = DocumentHelper.createDocument();

Document操作:

遍历students.xml

涉及的相关方法:

  1. Element getRootElement():Document的方法,用来获取根元素;
  2. List elements():Element的方法,用来获取所有孩子元素;
  3. String attributeValue(String name):Element的方法,用来获取指定名字的属性值;
  4. Element element(String name):Element的方法,用来获取第一个指定名字的子元素;
  5. String elementText(String name):Element的方法,用来获取第一个指定名字的子元素的文本内容。

分析步骤:

  1. 获取Document对象;
  2. 获取root元素;
  3. 获取root所有子元素
  4. 遍历每个student元素;
  • 打印student元素number属性;
  • 打印student元素的name子元素内容;
  • 打印student元素的age子元素内容;
  •  打印student元素的sex子元素内容。

      


http://www.kler.cn/a/560885.html

相关文章:

  • 离线环境如何玩转LLM?Ollama一键部署指南(Ubuntu)
  • Redis 集群的三种模式:一主一从、一主多从和多主多从
  • 【linux】全志t113平台修改ota升级配置文件,定向选择升级分区
  • AI赋能市场预测:ScriptEcho如何提升数据可视化效率
  • 自由学习记录(38)
  • 自动驾驶之BEV概述
  • 【UCB CS 61B SP24】Lecture 11 - Inheritance 4: Iterators, Object Methods学习笔记
  • 浅析 DeepSeek 开源的 FlashMLA 项目
  • 从三个维度了解 RPC(Remote Procedure Call,远程过程调用)
  • 算法打卡第十二弹——二叉树
  • Unity 协程
  • 【NLP 26、实践 ⑥ 引入bert,判断文本中是否有特定字符出现】
  • Linux 命令大全完整版(12)
  • 论文笔记:Scaling Sentence Embeddings with Large Language Models
  • 服务器能否拒绝非浏览器发起的HTTP请求?
  • 0224-leetcode-459.重复的子字符串、283. 移动零
  • unity学习53:UI的子容器:面板panel
  • 【网络安全】从零开始的CTF生活
  • 一文讲解Redis中的基本数据类型
  • postman并发测试某个接口