/*
Joe
30
Rob
29
*/
<%@page import="org.w3c.dom.Node, org.w3c.dom.Element, org.w3c.dom.Document, org.w3c.dom.NodeList, javax.xml.parsers.DocumentBuilder, javax.xml.parsers.DocumentBuilderFactory" %>
<%!
public boolean isTextNode(Node n)
{
return n.getNodeName().equals("#text");
}
%>
Parsing using the DOM
<%
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("http://localhost:8080/chapter02/people.xml");
%>
List of people
Name Age
<%
Element root = doc.getDocumentElement(); // "people" node
NodeList personNodes = root.getChildNodes(); // 2 "person" nodes
for (int i=0; i {
Node currentPerson = personNodes.item(i);
if (isTextNode(currentPerson)) // skip whitespace node
continue;
NodeList nameAndAge = currentPerson.getChildNodes(); // "name" and "age" nodes
%>
<%
for (int j=0; j {
Node currentItem = nameAndAge.item(j);
if ( isTextNode(currentItem))
continue;
%>
<%= currentItem.getFirstChild().getNodeValue() %>
<%
} // end of name & age loop
%>
<%
} // end person loop
%>