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

	}

}

运行

相关推荐
万行4 分钟前
机器学习&第一章
人工智能·python·机器学习·flask·计算机组成原理
2301_797312266 分钟前
学习java37天
开发语言·python
WJSKad123515 分钟前
果园树干识别与定位_faster-rcnn_x101-32x4d_fpn_1x_coco改进实践
python
深蓝电商API15 分钟前
Scrapy中间件实战:自定义请求头和代理池实现
python·scrapy·中间件
hui函数21 分钟前
Python系列Bug修复|如何解决 pip install 安装报错 invalid command ‘bdist_wheel’(缺少 wheel)问题
python·bug·pip
hui函数23 分钟前
Python系列Bug修复|如何解决 pip install -r requirements.txt 私有索引未设为 trusted-host 导致拒绝 问题
python·bug·pip
子午25 分钟前
【2026原创】动物识别系统~Python+深度学习+人工智能+模型训练+图像识别
人工智能·python·深度学习
o_insist30 分钟前
LangChain1.0 实现 PDF 文档向量检索全流程
人工智能·python·langchain
脑洞AI食验员35 分钟前
智能体来了:用异常与文件处理守住代码底线
人工智能·python
曲幽1 小时前
FastAPI登录验证:用OAuth2与JWT构筑你的API安全防线
python·fastapi·web·jwt·token·oauth2