JSP Parsing using the DOM : XML « JSP « Java






JSP Parsing using the DOM

/*
<people>
  <person>
    <name>Joe</name>
    <age>30</age>
  </person>
  <person>
    <name>Rob</name>
    <age>29</age>
  </person>
</people>

*/
<%@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");
  }
%>

<html>
  <head><title>Parsing using the DOM</title></head>
  <body>
    <%
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder        builder = factory.newDocumentBuilder();
      Document doc = builder.parse("http://localhost:8080/chapter02/people.xml");
    %>

    <h1>List of people</h1>
    <table border="1">
      <tr><th>Name</th><th>Age</th></tr>
        
    <%
      Element  root        = doc.getDocumentElement(); // "people" node
      NodeList personNodes = root.getChildNodes();     // 2 "person" nodes

      for (int i=0; i<personNodes.getLength(); i++)
      {
        Node currentPerson = personNodes.item(i);

        if (isTextNode(currentPerson)) // skip whitespace node
          continue;

        NodeList nameAndAge = currentPerson.getChildNodes(); // "name" and "age" nodes
    %>

    <tr>

    <%
        for (int j=0; j<nameAndAge.getLength(); j++ )
        {
          Node currentItem = nameAndAge.item(j);

          if ( isTextNode(currentItem)) 
            continue;
    %>
      <td><%= currentItem.getFirstChild().getNodeValue() %></td>
    <%
        } // end of name & age loop
    %>
    </tr>

    <%
      } // end person loop
    %>

    </table>
  </body>
</html>



           
       








Related examples in the same category

1.Using the Core XML tags
2.XML transformation
3.Performing XSL Transformations
4.JSP in pure XML generating conforming XHTML
5.XSLT In JSP
6.XSLT in JSP 2
7.JSP Parsing using JDOM
8.JSP Parsing using the DOM and JSTL
9.JSP and SAX
10.JSP Displaying a Subset in XML
11.JSP XML and XSLT transform
12.JSP List of data in the XML document
13.Deal With XML In JSP