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();
		}
		
		
		

	}

}

运行

相关推荐
ArabySide2 分钟前
【Java Web】过滤器的核心原理、实现与执行顺序配置
java·spring boot·java-ee
core5122 分钟前
Google A2A (Agent-to-Agent) 协议实战 —— 用 Python 构建“智能体互联网”
python·agent·a2a
zoujiahui_20184 分钟前
使用venv命令创建和使用python环境
开发语言·python
资深低代码开发平台专家7 分钟前
Python自动化:一键搞定“文件批量重命名”
python
追光天使8 分钟前
Python的后端框架
python
姚华军13 分钟前
利用Python算法,解析PDF文件并生成文档分块Chunks,追加到RagFlow知识库
开发语言·python·pdf·chunks·ragflow
dagouaofei23 分钟前
AI自动生成你的年度报告PPT
人工智能·python·powerpoint
嫂子的姐夫27 分钟前
01-selenium
爬虫·python·selenium·自动化
超级种码37 分钟前
SSE字符串以及Flux<String>中文乱码问题
java-ee·flux·sse