JSP学习笔记(四十一):使用dom4j读取简单的xml文件

dom4j下载地址:http://sourceforge.net/project/showfiles.php?group_id=16035

把下载到的dom4j-1.6.1.jar添加到项目中

新建一xml文件,建到WebRoot(这个是Web root folder,名字可能不同)/WEB-INF目录下,file.xml


<?xml version="1.0" encoding="UTF-8"?>
<books>
<book show="yes">
<title>Dom4j Tutorials</title>
</book>
<book show="yes">
<title>Lucene Studing</title>
</book>
<book show="no">
<title>Lucene in Action</title>
</book>
<owner>O'Reilly</owner>
</books>

 

新建一个类文件,Class1.java

import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Class1 {
public void readXml(String filepath) throws DocumentException {
SAXReader xmlReader
= new SAXReader();
File xmlFile
= new File(filepath);
Document doc
= xmlReader.read(xmlFile);//读取xml文件
Element rootElement
= doc.getRootElement();//得到xml文件的根节点,books
List l
= rootElement.elements();//得到根节点的子节点的集合
for (int i = 0; i < l.size(); i++) {
Element e
= (Element) l.get(i);
if (e.getName() == "book") {//只得到节点为book的,屏蔽节点owner
System.out.println(e.attributeValue(
"show"));//获取属性show的值
System.out.println(e.elementText(
"title"));//获取子节点名称为title的值
}
}
}
}

 

新建一个jsp文件调用,page.jsp

Class1 class1 = new Class1();
class1.readXml(request.getRealPath(
"/WEB-INF/file.xml"));

 

执行,控制台显示如下内容:

yes
Dom4j Tutorials
yes
Lucene Studing
no
Lucene in Action

转载于:https://www.cnblogs.com/modou/articles/1289383.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值