Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Monday, December 3, 2007

java code for JSP Parsing using the DOM

/*


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





<%
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;
%>

<%
} // end of name & age loop
%>


<%
} // end person loop
%>

NameAge
<%= currentItem.getFirstChild().getNodeValue() %>


No comments: