javaee dom4j读取xml文件

引入jar包

dom4j-1.6.1.jar

创建xml文件

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<books>
   <book id="1">
      <title ID="t1">背影</title>
      <price>88</price>
      <author>三毛</author>
   </book>
    <book id="2">
      <title>天龙八部</title>
      <price>99</price>
      <author>金庸</author>
   </book>
    <book id="3">
      <title>鹿鼎记</title>
      <price>108</price>
      <author>金庸</author>
   </book>
</books>

创建java文件

java 复制代码
package com.test.xml;

import java.io.InputStream;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ReadXml {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//1.获得xml文件的流对象(输入流)
		InputStream iStream=  ReadXml.class.getResourceAsStream("/Books.xml");
		//2.创建SAXReader解析器,读取xml文件到dom文档树对象中
		SAXReader saxReader=new SAXReader();
		try {
			Document document=  saxReader.read(iStream);
			
			//3.读取dom树中的节点
			
			//1)获得跟节点
			Element root=  document.getRootElement();
			
			//返回节点的名称
			System.out.println(root.getName());
			
			List<Element> bookElements=  root.elements();
			
			for(Element book:bookElements)
			{
				 System.out.println(book.getName());
				 
				 //根据节点的名称找孩子节点
				 Element title=book.element("title");				 		 
				 
				 System.out.println(title.getText()); //获得节点的内容
				 
				 //根据属性的名称找到属性
				 Attribute attribute= book.attribute("id");
				 //输出属性的值
				 System.out.println(attribute.getText());
				//输出属性的值方式2
				 System.out.println(book.attributeValue("id"));
				 
			}
			
			Element title=document.elementByID("t1");// id属性名是大写
			System.out.println(title.getText());
			
			
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		

	}

}

运行

相关推荐
曲幽6 分钟前
FastAPI实战:WebSocket长连接保持与心跳机制,从入门到填坑
javascript·python·websocket·keep-alive·fastapi·heartbeat·connection
好学且牛逼的马1 小时前
从“混沌初开”到“有序统一”:Java集合框架发展历程与核心知识点详解
前端·数据库·python
a1117761 小时前
快速制作 虚拟形象项目 MotionPNGTuber
python·live2d
一切尽在,你来1 小时前
AI大模型应用开发前置知识:Python迭代器和生成器深入详解
python·langchain·ai编程
小雨中_2 小时前
2.7 强化学习分类
人工智能·python·深度学习·机器学习·分类·数据挖掘
摩拜芯城IC3 小时前
ATSHA204A‑STUCZ CryptoAuthentication 安全认证芯片IC
python·安全
小雨中_3 小时前
2.4 贝尔曼方程与蒙特卡洛方法
人工智能·python·深度学习·机器学习·自然语言处理
MediaTea4 小时前
Python:可迭代对象(对象语义角色)
开发语言·python
skywalk81634 小时前
Diffusers 库介绍,它支持LTX-2模型
python
一个处女座的程序猿O(∩_∩)O5 小时前
Python函数参数*args和**kwargs完全指南:从入门到精通
开发语言·python