如何使用jsp教程的 DOM4J 读取 解析 xml文件
<?xml version="1.0" encoding="GB2312"?>
<RESULT>
<VALUE>
<NO>111cn.net</NO>
<ADDR>中国WEB第一站</ADDR>
</VALUE>
</RESULT>
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.111cn.net/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<body>
<%
使用 DOM4J 读取XML文件。
DOM4J
package test.xml;
import java.io.File;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class TestXMLByDOM4J {
public static void main(String[] args) {
long lasting = System.currentTimeMillis();
System.out.println("Read By DOM4J");
try {
File f = new File("text.xml");
// 解析器
SAXReader reader = new SAXReader();
// 读取并解析文件
Document doc = reader.read(f);
// 根节点
Element root = doc.getRootElement();
Element foo;
// 子节点遍历
for (Iterator i = root.elementIterator("VALUE"); i.hasNext();) {
foo = (Element) i.next();
System.out.print("车牌号码:" + foo.elementText("NO"));
System.out.println("车主地址:" + foo.elementText("ADDR"));
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("运行时间:" + (System.currentTimeMillis() - lasting) + "毫秒");
}
}
%>
</body>
</html>