如何使用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>