jsp教程解析xml文檔之使用 JDOM 讀取XML檔案
xml檔案:
<?xml version="1.0" encoding="GB2312"?>
<RESULT>
<VALUE>
<NO>A1234</NO>
<ADDR>四川省XX縣XX鎮XX路X段XX號</ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
<ADDR>四川省XX市XX鄉XX村XX組</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>
<%
JDOM
package test.xml;
import java.io.File;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
/**
* 使用 JDOM 讀取XML檔案。
*
*/
public class TestXMLByJDOM {
public static void main(String[] args) {
long lasting = System.currentTimeMillis();
System.out.println("Read By JDOM");
try {
// 構造
SAXBuilder builder = new SAXBuilder();
// 讀取文檔
Document doc = builder.build(new File("text.xml"));
// 得到根
Element foo = doc.getRootElement();
// 得到下級節點
List allChildren = foo.getChildren();
for (int i = 0; i < allChildren.size(); i++) {
System.out.print("車牌號碼:" + ((Element) allChildren.get(i)).getChild("NO").getText());
System.out.println("車主地址:" + ((Element) allChildren.get(i)).getChild("ADDR").getText());
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("已耗用時間:" + (System.currentTimeMillis() - lasting) + "毫秒");
}
}
%>
</body>
</html>