How to access element attributes using JSP and XML?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nathj
    Recognized Expert Contributor
    • May 2007
    • 937

    How to access element attributes using JSP and XML?

    Hi,

    I'm trying to develop what should be a simple jsp that reads an XML file, parses it and displays the content in a web page. Simple right?

    I have developed the XML and so any changes can be made there.

    The XML IS
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <featured>
    	<module type="Course Tool" title="Video Loader">
    		<description>Do you want to deliver high quality vidoe to your class? This tool will enable you to load video content quickly and easily.</description>
    		<img></img>
    	</module>
    	<module type="Course Tool" title="Content Block Loader">
    		<description>Class content is more engaging when it is beautifully presented - use this tool to easily present the information in the most appealing manner possible.</description>
    		<img></img>
    	</module>
    	<module type="Module" title="Art Gallery" priority="1">
    		<description>Showcasing the best student artwork from across the foundation.</description>
    		<img></img>
    	</module>
    	<module type="Module" title="Open Source">
    		<description>Details on software that is free to use. Categorised to help you find the best application available.</description>
    		<img></img>
    	</module>
    </featured>
    The JSP that reads this uses a little Java class so here they are:

    Java Class
    Code:
    package org.esf.utils;
    
    import java.io.File;
    
    import javax.servlet.jsp.JspWriter;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    import org.w3c.dom.Document;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    
    public class EsfDomParserBean implements java.io.Serializable
    {
    	public EsfDomParserBean()
    	{
    	}
    
    	public static Document getDocument(String file) throws Exception
    	{
    
    		// Step 1: create a DocumentBuilderFactory
    		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    
    		// Step 2: create a DocumentBuilder
    		DocumentBuilder db = dbf.newDocumentBuilder();
    
    		// Step 3: parse the input file to get a Document object
    		Document doc = db.parse(new File(file));
    		return doc;
    	}
    }
    The JSP
    Code:
    <div class="horizontalScroll" id="horizontalScroll" style="display:block;float:left;overflow:auto;overflow-x:scroll;overflow-y:hidden;height:250px">
    	<%
    		String esfXMLPath = blackboard.platform.plugin.PlugInUtil.getUri("ESFN", "Featured-Module", "FeaturedModule.xml");
    		Document doc = EsfDomParserBean.getDocument(esfXMLPath);
    		traverseTree(doc, out);
    	%>
    
    	<%!private void traverseTree(Node node, JspWriter out) throws Exception 
    		{
    			if (node == null) 
    			{
    				return;
    			}
    			int type = node.getNodeType();
    			String itemTitle = "";
    			switch (type) 
    			{
    				// handle document nodes
    				case Node.DOCUMENT_NODE: 
    				{
    					out.println("<div class=\"detailsContainer\" id=\"detailsContainer\" style=\"display:inline-block;float:left;\">");
    					traverseTree(((Document) node).getDocumentElement(), out);
    					break;
    				}
    				// handle element nodes
    				case Node.ELEMENT_NODE: 
    				{
    					String elementName = node.getNodeName();
    					
    					if (elementName.equalsIgnoreCase("module")) 
    					{
    						Element e = (Element) node;
    						if(e.hasAttribute("type") && e.hasAttribute("title"))
    						{
    							itemTitle = "<h3>" + e.getAttribute("type") + " " + e.getAttribute("title") + "</h3>";
    						}
    						else
    						{
    							itemTitle = "<h3>Cannot find type or title</h3>";
    						}
    						out.println("</div><div class=\"detailsContainer\" id=\"detailsContainer\" style=\"display:inline-block;float:left;\">");
    					}
    					NodeList childNodes = node.getChildNodes();
    					if (childNodes != null) 
    					{
    						int length = childNodes.getLength();
    						for (int loopIndex = 0; loopIndex < length; loopIndex++) 
    						{
    							traverseTree(childNodes.item(loopIndex), out);
    						}
    					}
    					break;
    				}
    				// handle text nodes
    				case Node.TEXT_NODE: 
    				{
    					String data = node.getNodeValue().trim();
    					if ((data.indexOf("\n") < 0) && (data.length() > 0)) 
    					{
    						if(data.toUpperCase().contains(".jpg")||data.toUpperCase().contains(".jpeg")||data.toUpperCase().contains(".png"))
    						{
    							out.println("<span class=\"rightContainer\" id=\"rightContainer\" style=\"display:inline;float:right\"><img src=\"" + data + "\"/></span>");
    						}
    						else
    						{
    							
    							out.println("<span class=\"leftContainer\" id=\"leftContainer\" style=\"display:inline;float:left\">" + itemTitle +  data + "</span>");
    						}
    					}
    				}
    			}
    		}
    %>
    </div>
    I need to get the type and title attributes out of the module element so that I can write them out in a <h3> tags inside the leftContainer span. The trouble is I can't find the way to retrieve this information. I've been reading around the web for a couple of days now and I'm not finding anything on this.

    Does anyone have a great tip/pointer for me or even a tutorial where this has been done already?

    Cheers
    nathj
  • nathj
    Recognized Expert Contributor
    • May 2007
    • 937

    #2
    Hi,

    Here's a quick update on the progress I'm making. As such the question has changed slightly now.

    Code:
    <%
    	String esfXMLPath = blackboard.platform.plugin.PlugInUtil.getUri("ESFN", "Featured-Module", "FeaturedModule.xml");
    	Document doc = EsfDomParserBean.getDocument(esfXMLPath);
    	//traverseTree(doc, out);
    	Element root = doc.getDocumentElement();
    	NodeList moduleList = root.getChildNodes();
    	
    	StringBuilder output = new StringBuilder("<div class=\"horizontalScroll\" id=\"horizontalScroll\" style=\"display:block;float:left;overflow:auto;overflow-x:scroll;overflow-y:hidden;height:250px\">");
    	
    	for(int i = 0; i < moduleList.getLength(); i++)
    	{
    		Node module = moduleList.item(i);
    		if(module.getNodeName().equals("module"))
    		{
    			output.append("<div class=\"detailsContainer\" id=\"detailsContainer\" style=\"display:inline-block;float:left;\">");
    			Element section = (Element) moduleList.item(i);
    			String title= "<h3>" + section.getAttribute("type") + "&nbsp;&mdash;&nbsp;" + section.getAttribute("title") + "</h3>";
    			
    			NodeList moduleDetails = module.getChildNodes();
    			for(int j = 0; j < moduleDetails.getLength(); j++)
    			{
    				Node moduleDetail = moduleDetails.item(j);
    				if(moduleDetail.getNodeName().equalsIgnoreCase("description"))
    				{
    					output.append("<span class=\"leftContainer\" id=\"leftContainer\" style=\"display:inline;float:left\">" + title + moduleDetail.getNodeValue() + "</span>");
    				}
    				if(moduleDetail.getNodeName().equalsIgnoreCase("img"))
    				{
    					output.append("<span class=\"rightContainer\" id=\"rightContainer\" style=\"display:inline;float:right\"><img src=\"" + moduleDetail.getNodeValue() + "\"/></span>");
    				}
    			}
    			output.append("</div>");
    		}
    	}
    	output.append("</div>");
    %>
    <%=output.toString() %>
    Now I'm getting the type and title out of the module element which is great. The trouble is that I now am not getting the data out of the XML, so I'm not seeing the description coming out.

    Any help on this is greatly appreciated.

    Cheers
    nathj

    Comment

    • nathj
      Recognized Expert Contributor
      • May 2007
      • 937

      #3
      Hi,

      A little bit of perseverance and some playing around I have it cracked.

      Code:
      <%
      	String esfXMLPath = blackboard.platform.plugin.PlugInUtil.getUri("ESFN", "Featured-Module", "FeaturedModule.xml");
      	Document doc = EsfDomParserBean.getDocument(esfXMLPath);
      	//traverseTree(doc, out);
      	Element root = doc.getDocumentElement();
      	NodeList moduleList = root.getChildNodes();
      	
      	StringBuilder output = new StringBuilder("<div class=\"horizontalScroll\" id=\"horizontalScroll\" style=\"display:block;float:left;overflow:auto;overflow-x:scroll;overflow-y:hidden;height:250px\">");
      	
      	for(int i = 0; i < moduleList.getLength(); i++)
      	{
      		Node module = moduleList.item(i);
      		if(module.getNodeName().equals("module"))
      		{
      			output.append("<div class=\"detailsContainer\" id=\"detailsContainer\" style=\"display:inline-block;float:left;\">");
      			Element section = (Element) moduleList.item(i);
      			String title= "<h3>" + section.getAttribute("type") + "&nbsp;&mdash;&nbsp;" + section.getAttribute("title") + "</h3>";
      			
      			NodeList moduleDetails = module.getChildNodes();
      			for(int j = 0; j < moduleDetails.getLength(); j++)
      			{
      				Node moduleDetail = moduleDetails.item(j);
      				if(moduleDetail.getNodeName().equalsIgnoreCase("description"))
      				{
      					output.append("<span class=\"leftContainer\" id=\"leftContainer\" style=\"display:inline;float:left\">" + title + "<p>" + moduleDetail.getChildNodes().item(0).getNodeValue() + "</p></span>");
      				}
      				if(moduleDetail.getNodeName().equalsIgnoreCase("img"))
      				{
      					output.append("<span class=\"rightContainer\" id=\"rightContainer\" style=\"display:inline;float:right\"><img src=\"" + moduleDetail.getChildNodes().item(0).getNodeValue() + "\"/></span>");
      				}
      			}
      			output.append("</div>");
      		}
      	}
      	output.append("</div>");
      %>
      <%=output.toString() %>
      I admit I need some error trapping in here - particularly to cater for NullPointerExce ptions but the basics are there thanks to :



      Thanks
      nathj

      Comment

      Working...