JSP Parsing using the DOM : XML « JSP « Java

JSP Parsing using the DOM


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

  <head><title>Parsing using the DOM</title></head>
      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">
      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

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


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

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

      } // end person loop



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