473,406 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

How to access element attributes using JSP and XML?

nathj
938 Expert 512MB
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
Expand|Select|Wrap|Line Numbers
  1.  
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <featured>
  4.     <module type="Course Tool" title="Video Loader">
  5.         <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>
  6.         <img></img>
  7.     </module>
  8.     <module type="Course Tool" title="Content Block Loader">
  9.         <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>
  10.         <img></img>
  11.     </module>
  12.     <module type="Module" title="Art Gallery" priority="1">
  13.         <description>Showcasing the best student artwork from across the foundation.</description>
  14.         <img></img>
  15.     </module>
  16.     <module type="Module" title="Open Source">
  17.         <description>Details on software that is free to use. Categorised to help you find the best application available.</description>
  18.         <img></img>
  19.     </module>
  20. </featured>
  21.  
The JSP that reads this uses a little Java class so here they are:

Java Class
Expand|Select|Wrap|Line Numbers
  1. package org.esf.utils;
  2.  
  3. import java.io.File;
  4.  
  5. import javax.servlet.jsp.JspWriter;
  6. import javax.xml.parsers.DocumentBuilder;
  7. import javax.xml.parsers.DocumentBuilderFactory;
  8.  
  9. import org.w3c.dom.Document;
  10. import javax.xml.parsers.*;
  11. import org.w3c.dom.*;
  12.  
  13. public class EsfDomParserBean implements java.io.Serializable
  14. {
  15.     public EsfDomParserBean()
  16.     {
  17.     }
  18.  
  19.     public static Document getDocument(String file) throws Exception
  20.     {
  21.  
  22.         // Step 1: create a DocumentBuilderFactory
  23.         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  24.  
  25.         // Step 2: create a DocumentBuilder
  26.         DocumentBuilder db = dbf.newDocumentBuilder();
  27.  
  28.         // Step 3: parse the input file to get a Document object
  29.         Document doc = db.parse(new File(file));
  30.         return doc;
  31.     }
  32. }
  33.  
The JSP
Expand|Select|Wrap|Line Numbers
  1. <div class="horizontalScroll" id="horizontalScroll" style="display:block;float:left;overflow:auto;overflow-x:scroll;overflow-y:hidden;height:250px">
  2.     <%
  3.         String esfXMLPath = blackboard.platform.plugin.PlugInUtil.getUri("ESFN", "Featured-Module", "FeaturedModule.xml");
  4.         Document doc = EsfDomParserBean.getDocument(esfXMLPath);
  5.         traverseTree(doc, out);
  6.     %>
  7.  
  8.     <%!private void traverseTree(Node node, JspWriter out) throws Exception 
  9.         {
  10.             if (node == null) 
  11.             {
  12.                 return;
  13.             }
  14.             int type = node.getNodeType();
  15.             String itemTitle = "";
  16.             switch (type) 
  17.             {
  18.                 // handle document nodes
  19.                 case Node.DOCUMENT_NODE: 
  20.                 {
  21.                     out.println("<div class=\"detailsContainer\" id=\"detailsContainer\" style=\"display:inline-block;float:left;\">");
  22.                     traverseTree(((Document) node).getDocumentElement(), out);
  23.                     break;
  24.                 }
  25.                 // handle element nodes
  26.                 case Node.ELEMENT_NODE: 
  27.                 {
  28.                     String elementName = node.getNodeName();
  29.  
  30.                     if (elementName.equalsIgnoreCase("module")) 
  31.                     {
  32.                         Element e = (Element) node;
  33.                         if(e.hasAttribute("type") && e.hasAttribute("title"))
  34.                         {
  35.                             itemTitle = "<h3>" + e.getAttribute("type") + " " + e.getAttribute("title") + "</h3>";
  36.                         }
  37.                         else
  38.                         {
  39.                             itemTitle = "<h3>Cannot find type or title</h3>";
  40.                         }
  41.                         out.println("</div><div class=\"detailsContainer\" id=\"detailsContainer\" style=\"display:inline-block;float:left;\">");
  42.                     }
  43.                     NodeList childNodes = node.getChildNodes();
  44.                     if (childNodes != null) 
  45.                     {
  46.                         int length = childNodes.getLength();
  47.                         for (int loopIndex = 0; loopIndex < length; loopIndex++) 
  48.                         {
  49.                             traverseTree(childNodes.item(loopIndex), out);
  50.                         }
  51.                     }
  52.                     break;
  53.                 }
  54.                 // handle text nodes
  55.                 case Node.TEXT_NODE: 
  56.                 {
  57.                     String data = node.getNodeValue().trim();
  58.                     if ((data.indexOf("\n") < 0) && (data.length() > 0)) 
  59.                     {
  60.                         if(data.toUpperCase().contains(".jpg")||data.toUpperCase().contains(".jpeg")||data.toUpperCase().contains(".png"))
  61.                         {
  62.                             out.println("<span class=\"rightContainer\" id=\"rightContainer\" style=\"display:inline;float:right\"><img src=\"" + data + "\"/></span>");
  63.                         }
  64.                         else
  65.                         {
  66.  
  67.                             out.println("<span class=\"leftContainer\" id=\"leftContainer\" style=\"display:inline;float:left\">" + itemTitle +  data + "</span>");
  68.                         }
  69.                     }
  70.                 }
  71.             }
  72.         }
  73. %>
  74. </div>
  75.  
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
Jan 21 '11 #1

✓ answered by nathj

Hi,

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

Expand|Select|Wrap|Line Numbers
  1. <%
  2.     String esfXMLPath = blackboard.platform.plugin.PlugInUtil.getUri("ESFN", "Featured-Module", "FeaturedModule.xml");
  3.     Document doc = EsfDomParserBean.getDocument(esfXMLPath);
  4.     //traverseTree(doc, out);
  5.     Element root = doc.getDocumentElement();
  6.     NodeList moduleList = root.getChildNodes();
  7.  
  8.     StringBuilder output = new StringBuilder("<div class=\"horizontalScroll\" id=\"horizontalScroll\" style=\"display:block;float:left;overflow:auto;overflow-x:scroll;overflow-y:hidden;height:250px\">");
  9.  
  10.     for(int i = 0; i < moduleList.getLength(); i++)
  11.     {
  12.         Node module = moduleList.item(i);
  13.         if(module.getNodeName().equals("module"))
  14.         {
  15.             output.append("<div class=\"detailsContainer\" id=\"detailsContainer\" style=\"display:inline-block;float:left;\">");
  16.             Element section = (Element) moduleList.item(i);
  17.             String title= "<h3>" + section.getAttribute("type") + "&nbsp;&mdash;&nbsp;" + section.getAttribute("title") + "</h3>";
  18.  
  19.             NodeList moduleDetails = module.getChildNodes();
  20.             for(int j = 0; j < moduleDetails.getLength(); j++)
  21.             {
  22.                 Node moduleDetail = moduleDetails.item(j);
  23.                 if(moduleDetail.getNodeName().equalsIgnoreCase("description"))
  24.                 {
  25.                     output.append("<span class=\"leftContainer\" id=\"leftContainer\" style=\"display:inline;float:left\">" + title + "<p>" + moduleDetail.getChildNodes().item(0).getNodeValue() + "</p></span>");
  26.                 }
  27.                 if(moduleDetail.getNodeName().equalsIgnoreCase("img"))
  28.                 {
  29.                     output.append("<span class=\"rightContainer\" id=\"rightContainer\" style=\"display:inline;float:right\"><img src=\"" + moduleDetail.getChildNodes().item(0).getNodeValue() + "\"/></span>");
  30.                 }
  31.             }
  32.             output.append("</div>");
  33.         }
  34.     }
  35.     output.append("</div>");
  36. %>
  37. <%=output.toString() %>
  38.  
I admit I need some error trapping in here - particularly to cater for NullPointerExceptions but the basics are there thanks to :
http://groups.google.com/group/Googl...d9b39322?pli=1
http://www.java2s.com/Code/JavaAPI/o...tNodeValue.htm

Thanks
nathj

2 5146
nathj
938 Expert 512MB
Hi,

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

Expand|Select|Wrap|Line Numbers
  1. <%
  2.     String esfXMLPath = blackboard.platform.plugin.PlugInUtil.getUri("ESFN", "Featured-Module", "FeaturedModule.xml");
  3.     Document doc = EsfDomParserBean.getDocument(esfXMLPath);
  4.     //traverseTree(doc, out);
  5.     Element root = doc.getDocumentElement();
  6.     NodeList moduleList = root.getChildNodes();
  7.  
  8.     StringBuilder output = new StringBuilder("<div class=\"horizontalScroll\" id=\"horizontalScroll\" style=\"display:block;float:left;overflow:auto;overflow-x:scroll;overflow-y:hidden;height:250px\">");
  9.  
  10.     for(int i = 0; i < moduleList.getLength(); i++)
  11.     {
  12.         Node module = moduleList.item(i);
  13.         if(module.getNodeName().equals("module"))
  14.         {
  15.             output.append("<div class=\"detailsContainer\" id=\"detailsContainer\" style=\"display:inline-block;float:left;\">");
  16.             Element section = (Element) moduleList.item(i);
  17.             String title= "<h3>" + section.getAttribute("type") + "&nbsp;&mdash;&nbsp;" + section.getAttribute("title") + "</h3>";
  18.  
  19.             NodeList moduleDetails = module.getChildNodes();
  20.             for(int j = 0; j < moduleDetails.getLength(); j++)
  21.             {
  22.                 Node moduleDetail = moduleDetails.item(j);
  23.                 if(moduleDetail.getNodeName().equalsIgnoreCase("description"))
  24.                 {
  25.                     output.append("<span class=\"leftContainer\" id=\"leftContainer\" style=\"display:inline;float:left\">" + title + moduleDetail.getNodeValue() + "</span>");
  26.                 }
  27.                 if(moduleDetail.getNodeName().equalsIgnoreCase("img"))
  28.                 {
  29.                     output.append("<span class=\"rightContainer\" id=\"rightContainer\" style=\"display:inline;float:right\"><img src=\"" + moduleDetail.getNodeValue() + "\"/></span>");
  30.                 }
  31.             }
  32.             output.append("</div>");
  33.         }
  34.     }
  35.     output.append("</div>");
  36. %>
  37. <%=output.toString() %>
  38.  
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
Jan 21 '11 #2
nathj
938 Expert 512MB
Hi,

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

Expand|Select|Wrap|Line Numbers
  1. <%
  2.     String esfXMLPath = blackboard.platform.plugin.PlugInUtil.getUri("ESFN", "Featured-Module", "FeaturedModule.xml");
  3.     Document doc = EsfDomParserBean.getDocument(esfXMLPath);
  4.     //traverseTree(doc, out);
  5.     Element root = doc.getDocumentElement();
  6.     NodeList moduleList = root.getChildNodes();
  7.  
  8.     StringBuilder output = new StringBuilder("<div class=\"horizontalScroll\" id=\"horizontalScroll\" style=\"display:block;float:left;overflow:auto;overflow-x:scroll;overflow-y:hidden;height:250px\">");
  9.  
  10.     for(int i = 0; i < moduleList.getLength(); i++)
  11.     {
  12.         Node module = moduleList.item(i);
  13.         if(module.getNodeName().equals("module"))
  14.         {
  15.             output.append("<div class=\"detailsContainer\" id=\"detailsContainer\" style=\"display:inline-block;float:left;\">");
  16.             Element section = (Element) moduleList.item(i);
  17.             String title= "<h3>" + section.getAttribute("type") + "&nbsp;&mdash;&nbsp;" + section.getAttribute("title") + "</h3>";
  18.  
  19.             NodeList moduleDetails = module.getChildNodes();
  20.             for(int j = 0; j < moduleDetails.getLength(); j++)
  21.             {
  22.                 Node moduleDetail = moduleDetails.item(j);
  23.                 if(moduleDetail.getNodeName().equalsIgnoreCase("description"))
  24.                 {
  25.                     output.append("<span class=\"leftContainer\" id=\"leftContainer\" style=\"display:inline;float:left\">" + title + "<p>" + moduleDetail.getChildNodes().item(0).getNodeValue() + "</p></span>");
  26.                 }
  27.                 if(moduleDetail.getNodeName().equalsIgnoreCase("img"))
  28.                 {
  29.                     output.append("<span class=\"rightContainer\" id=\"rightContainer\" style=\"display:inline;float:right\"><img src=\"" + moduleDetail.getChildNodes().item(0).getNodeValue() + "\"/></span>");
  30.                 }
  31.             }
  32.             output.append("</div>");
  33.         }
  34.     }
  35.     output.append("</div>");
  36. %>
  37. <%=output.toString() %>
  38.  
I admit I need some error trapping in here - particularly to cater for NullPointerExceptions but the basics are there thanks to :
http://groups.google.com/group/Googl...d9b39322?pli=1
http://www.java2s.com/Code/JavaAPI/o...tNodeValue.htm

Thanks
nathj
Jan 21 '11 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Mike Clair | last post by:
Hey, I'm having an issue with CSS, JS and the DOM. It's gonna drive me batty. I am trying to access the properties of a layer in JS which have been initially set in an external CSS. The problem...
2
by: Erwin S. Andreasen | last post by:
Hi, I have a web application where window A opens window B (same site). B later wants to do something depending on whether the window A, window.opener.document.domain, has changed. However,...
1
by: Wayne Lian via .NET 247 | last post by:
Hi all, Just wonder anyone have encountered this problem before?I tried using XMLSPY debugger and I can get the correct outputfor my XSLT transformation, however in .net, aftertransformation the...
3
by: Michael Iantosca | last post by:
I have a custom attribute that I attach to certain pages in my application and I want to inspect each page request as it is made to see if the custom attribute is attached to the underlying page...
1
by: serge calderara | last post by:
Dear all, where is the place to get the list of each valid attributes for individual Element of a confi file or Html page view? thanks fr your help regards serge
4
by: joewhitehair | last post by:
Using a schema, I created classes for my web service using the XSD.exe tool. With the classes I then wrote a web service function, but the WSDL that is generated has different minOccurs and...
2
by: Mikus Sleiners | last post by:
I want to create xml document that looks like this: <?xml version="1.0" encoding="utf-16"?> <Draft xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"...
2
by: matthewjbarr | last post by:
Sorry for cross-posting, but I posted this in the PHP group and think it probably should have been here - think maybe I should be looking at XPath expressions to solve the problem. E.g. something...
3
by: Beorne | last post by:
In the classes I develop my attributes are always private and are exposed using properties. directly or to access the attributes using the properties? Does "wrapper" setter/getter properties...
2
by: cloftis | last post by:
Using VS2003, VB and MSHTML, Using an HTMLSpanElement I want to enumerate the attributes of a SPAN tag. 1 'For testing sake 2 Dim strMarkup as String = "<span attr1='somevalue'...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.