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

	}

}

运行

相关推荐
全栈练习生3 小时前
AI Agent 沙箱
python·ai
SEO_juper4 小时前
用 Python 写一个 GEO 可见性检查脚本:你的网站现在能被 AI 引用吗
开发语言·人工智能·爬虫·python·seo·外贸独立站
用户8356290780516 小时前
使用 Python 对 Excel 工作表进行排序
后端·python
for_ever_love__6 小时前
MySQL 全文索引实战:FULLTEXT、ngram 中文分词与 MATCH AGAINST 到底该怎么用
java·python·mysql·全文检索·分词·索引·ngram
用户8356290780516 小时前
使用 Python 合并 PowerPoint 演示文稿
后端·python
weixin_461769406 小时前
VS Code 中创建 Jupyter 文件(.ipynb)
ide·python·jupyter
2601_966949656 小时前
多市场量化策略的数据接口应该如何设计:从数据层架构到策略接入
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
全栈弄潮儿7 小时前
Python实战第1期:Python环境搭建与第一个程序
python
心易行者7 小时前
Agent应用+API端点商业化进阶实战:从单体智能体到可付费调用的API全流程
运维·服务器·人工智能·python·apache
weixin199701080167 小时前
《1688图片空间API踩坑:img.upload 与 album.* 的防盗链与CDN缓存问题》(附Python源码)
开发语言·python·缓存