JSP-XML DataGrid I
This is a simple procedure to show how to use an XML file as datasource to
build a datagrid in JSP. This code basically shows how to display and
navigate/page-thru and xml data file
Figure 1
![]()
Consider an xml file (plants.xml) of the following format
<CATALOG>
<PLANT>
<COMMON>Bloodroot</COMMON>
<BOTANICAL>Sanguinaria canadensis</BOTANICAL>
<ZONE>4</ZONE>
<LIGHT>Mostly Shady</LIGHT>
<PRICE>$2.44</PRICE>
<AVAILABILITY>031599</AVAILABILITY>
</PLANT>
<PLANT></PLANT>
</CATALOG>
If you want to generate a datagrid (figure 1) that will display and navigate
through the plants information, simple procedure to accomplish this using java
in JSP will be as follows:
public String getDataGrid(String fileName, int startIndex,int pageSize, String script){ int stopIndex; //the stop index used to control the pagesize int totalRecs; //total number of palnts String bgColor="white"; //grid background color try{ //Step 2: Get your DOM document. //Get Document Builder Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the Builder DocumentBuilder builder = factory.newDocumentBuilder(); //Get your DOM document by loading your plants file Document document = builder.parse(new java.io.File(fileName)); //Get all plants NodeList nodeList = document.getElementsByTagName("PLANT"); totalRecs = nodeList.getLength(); //check the number of records returned if(totalRecs<1){ return "No plants in file"; } //validate start index if(startIndex<0){ startIndex=0; } //set your stop index stopIndex = startIndex+pageSize; //validate your stop index if (stopIndex>totalRecs-1){ stopIndex=totalRecs-1 ; } //build your string StringBuffer buf = new StringBuffer(); buf.append("Records " + (startIndex+1) + " to " + (stopIndex+1) + " (" + totalRecs + " records)<hr size=\"1\" noshade>"); buf.append("<table border=0 cellspacing=1 cellpadding=1 bgcolor=gray >"); //print headers buf.append("<tr bgcolor=teal>"); int i,j,k; //NodeList nodeList2 = nodeList.item(0).getChildNodes(); for (i=0;i<nodeList.item(0).getChildNodes().getLength();i++){ Node node=nodeList.item(0).getChildNodes().item(i); if(node.getNodeType()==Node.ELEMENT_NODE){ buf.append("<td><b>" + node.getNodeName() + "</b></td>"); } } buf.append("</tr>"); //navigate list and print records for (i=startIndex; i<=stopIndex;i++){ //alternate your rows background colors if(bgColor=="#cccccc"){ bgColor="white"; }else{ bgColor="#cccccc"; } buf.append("<tr bgcolor="+ bgColor +">"); for (j=0; j<nodeList.item(i).getChildNodes().getLength();j++){ Node thisNode = nodeList.item(i).getChildNodes().item(j); if(thisNode.getNodeType()==Node.ELEMENT_NODE){ buf.append("<td>"+ getNodeValue(thisNode) + "</td>"); } } buf.append("</tr>"); } buf.append("</table>"); //print navigation controls .... } catch (Exception e) { return(e.toString()); } }