JSP & JSTL: Setting a Variable to the Content of an XPath

I had a problem in JSP and JSTL where I could not get a core variable to contain the content of an XML XPath expression.

Following a combination of reading a book, searching the Internet and speaking to a colleague, I found two solutions to my problem, but unfortunately not an answer to the question of why my original code does not work.

Here is a code: fragment

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>

<head>
  <title>JSTL / JSP test</title>
</head>

<body>

<%--c:import url="/xml_files/document.xml" var="url"/>
<x:parse xml="${url}" var="doc" scope="page" /--%>

<x:parse var="doc" scope="page">
  <root_element>
    <more_elements>
      <element_name>the element value</element_name>
    </more_elements>
  </root_element>
</x:parse>

<table>
  <tr>
    <td>This doesn't work; why?</td>
    <x:set var="element_value1" scope="page"
        select="string($doc/root_element/more_elements/element_name/text())"/>
    <td><c:out value="${element_value1}"/></td>
  </tr>
  <tr>
    <td>This does work</td>
    <x:set var="element_node2" scope="page"
       select="$doc/root_element/more_elements/element_name"/>
    <x:set var="element_value2" scope="page"
        select="string($element_node2/text())"/>
    <td><c:out value="${element_value2}"/></td>
  </tr>
  <tr>
    <td>This works too</td>
    <c:set var="element_value3" scope="page">
      <x:out select="$doc/root_element/more_elements/element_name"/>
    </c:set>
    <td><c:out value="${element_value3}"/></td>
  </tr>
</table>

</body>
</html>

This was run on Apache Tomcat 6.0.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: