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