Võ Văn Hải's blog

Chỉ có một điều tuyệt đối đó là mọi thứ đều tương đối…

Dùng DOM để hiển thị tài liệu trong JSP

Tạo file peoples.xml có nội dung sau

<?xml version=”1.0″ encoding=”utf-8″?>
<people>
<person>
<name>Joe</name>
<age>30</age>
</person>
<person>
<name>Rob</name>
<age>29</age>
</person>
<person>
<name>Tý</name>
<age>10</age>
</person>
<person>
<name>Tèo</name>
<age>9</age>
</person>
</people>

Tạo file index.jsp có nội dung sau

<%@ page import=”org.jdom.Element,
org.jdom.Document,
org.jdom.input.SAXBuilder,
java.util.List,
java.util.Iterator”
%>
<!– remember to change the url of the xml file–>
<%
SAXBuilder builder  = new SAXBuilder();
Document   doc      = builder.build(“http://localhost:8080/XML_JSP/dom/peoples.xml&#8221;);
List      children = doc.getRootElement().getChildren(); // 2 person nodes
Iterator   iter     = children.iterator();
%>

<html>
<head><title>Parsing using JDOM</title></head>
<body>
<h1>List of people</h1>

<table border=”1″ width=”50%”>
<tr><th>Name</th><th>Age</th></tr>

<%
while (iter.hasNext()) // for each “person” node
{
Element  currentItem = (Element) iter.next();     // each “person”
List     nameAndAge  = currentItem.getChildren();
Iterator nameAgeIter = nameAndAge.iterator();
%>
<tr>
<%
while ( nameAgeIter.hasNext() )
{
Element child = (Element) nameAgeIter.next(); // “name” or “age”
%>
<td><%= child.getText() %></td>
<%
}
}
%>
</tr>
</table>
</body>
</html>

Kết quả khi duyệt  file index:
https://vovanhai.files.wordpress.com/2008/09/dom_jsp.png

2 Responses to “Dùng DOM để hiển thị tài liệu trong JSP”

  1. ngoclinh said

    neu hien ra ds tu sql thi co khac lam ko

  2. Thái said

    Sao các bài demo cua thầy không up lên cùng bài luôn ah?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: