Parsing an XML document using JSTL
AmazonMacbethSpanish.xml document is parsed, and a
segment of the document that contains quotations is selected. A forEach tag is used to loop through each instance of a quote and display the results in a table on an HTML page. If you followed along through the previous example, much of the startup code is repeated. Because the servlet is generated and not hand-coded, the
patterns in the code are largely the same, with core code towards the end of the servlet making the JSP unique. If you were comfortable with the setup code from the previous servlet example, you can skip down to the part of the code that defines the org.apache.taglibs.standard.tag.el.xml.ParseTag and begins parsing the document.
Each taglib directive defines a uri and a prefix. As in the
previous example, the c prefix is used for core library actions such as c:import.The x prefix is used for the XML library x
arse action. Next, an HTML page is createdand a simple HTML page head with a page title is defined. Next, the HTMLbody of the page begins with the import of an XML document. The XML document
is assigned a variable name of xmlToParse. Parsing the XML document is facilitatedthrough the parse tag, and the parsed org.w3c.dom.Document object is assigned to a variable named parsedXML. Next, an HTML table is defined and Author, Source, and Quotation headings are defined in the table.
The forEach tag uses an EL expression to pass the org.w3c.dom.Document object into the select attribute. The rest of the select attribute retrieves all of the nested elements under the /quotedoc/quotelist/* XPath expression. The
results of a select are not implicitly sent to the JspWriter, which is actually a good thing, because we only want to send some of the select statement results out to the browser screen. The Author attribute, Source attribute (Defined by the
@ XPath Expression), and the contents of the text associated with each element
(defined by the . XPath expression) are sent to the JspWriter using the out tag.
Example:
<<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core” %>
<%@ taglib prefix=”x” uri=”http://java.sun.com/jstl/xml” %>
JSP Page Parsing Example
arse var=”parsedXML” xml=”${xmlToParse}” />