CSCI 5733
XML Application Development
Spring 2006
Suggested Solution to Homework #4

(1) For example:

<html>
    <head>
        <title>XMLHTTP example</title>
        <script type="text/javascript" language="javascript">

            var http_request = false;

            function makeRequest(url) {

                if (window.XMLHttpRequest) { // Mozilla, Safari,...
                    http_request = new XMLHttpRequest();
                } else if (window.ActiveXObject) { // IE
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                }
                http_request.onreadystatechange = writeNews;
                http_request.open('GET', url, true);
                http_request.send(null);

            }

            function writeNews() {

                if (http_request.readyState == 4) {
                    if (http_request.status == 200) {
                  var outputTable = '';
                 
                  outputDiv = document.getElementById('news');
                  outputDiv.innerHTML = '';

                  var entries = http_request.responseXML.documentElement.getElementsByTagName("entry");

                  outputTable = "<table border='1' cellpadding='3'>\n";
                  outputTable += "<tr><td style='font-weight:bold'>time</td><td style='font-weight:bold'>news</td></tr>\n";

                  for (i=0; i < entries.length; i++){
                     outputTable += "<tr><td>"
                        + entries[i].getElementsByTagName("harvesttime")[0].firstChild.nodeValue
                        + "</td><td><a href='"
                        + entries[i].getElementsByTagName("url")[0].firstChild.nodeValue
                        + "'>"
                        + entries[i].getElementsByTagName("headline")[0].firstChild.nodeValue
                        + "</a></td></tr>\n";
                  }
                  outputTable += "</table>\n";

                  outputDiv.innerHTML = outputTable

                    } else {
                    }
                }   //   writeNews

            }
        </script>
    </head>
    <body style="font-family:verdana; background:#ccccff">
      Click to get news:
        <a href="" onclick="makeRequest('http://dcm.cl.uh.edu/yue/courses/xml/notes/general/news.pl?topic=China'); return false;">China</a>,

        <a href="" onclick="makeRequest('http://dcm.cl.uh.edu/yue/courses/xml/notes/general/news.pl?topic=India'); return false;">India</a>,

        <a href="" onclick="makeRequest('http://dcm.cl.uh.edu/yue/courses/xml/notes/general/news.pl?topic=Canada'); return false;">Canada</a>.
   <hr />
   <div id="news">News to come.</div>
    </body>

</html>

(2)

(a) //person[@gender='M' and contains(link/@children, //person[link/@children]/@ssn)].

(b) //person[count(email) = 2]

(c) //person[not(preceding::person)]

(d) //person[@ssn = //person/link/@father or @ssn=//person/link/@mother]

(3) For example:

h4.jsp:

<%@ page import="javax.xml.parsers.*"
%><%@ page import="javax.xml.transform.*"
%><%
   String xmlSourceUrl = "http://dcm.cl.uh.edu/yue/courses/xml/notes/general/news.pl?topic=";
   String xslSourceFilename = "";

   //   self: the name of this script.
   String self = request.getRequestURI();
   //   Assume windows system: \ for directory separator.  Assume that the xsl files and jsp files are stored
   //   in the same directory.
   String scriptDirectory = application.getRealPath(self).substring(0, application.getRealPath(self).lastIndexOf("\\")+1);
   String scriptFilename = self.substring(self.lastIndexOf("/")+1);

   //   get news topic
   String topic = request.getParameter("topic");
   if (topic == null) topic = "";
  
   //   get format value.
   String format = request.getParameter("format");
   if (format == null) format = "";

   if ("html".equalsIgnoreCase(format)) {
      response.setContentType("text/html");
      xslSourceFilename = "courses/xml/spring2006/h4html.xsl";
   }
   else if ("xml".equalsIgnoreCase(format)) {
      response.setContentType("text/xml");
      xslSourceFilename = "courses/xml/spring2006/h4xml.xsl";
   }
   else {
      //   default is xml.
      response.setContentType("text/xml");
      xslSourceFilename = "courses/xml/spring2006/h4xml.xsl";
   }
  
   //   Transform and output.
   try
    {  
      javax.xml.transform.TransformerFactory tFactory =
                javax.xml.transform.TransformerFactory.newInstance();
      // Get the XML input document and the stylesheet, both in the servlet
      // engine document directory.
      javax.xml.transform.Source xmlSource =
                new javax.xml.transform.stream.StreamSource
                             (new java.net.URL(xmlSourceUrl + topic).openStream());
      javax.xml.transform.Source xslSource =
                new javax.xml.transform.stream.StreamSource
                            (new java.net.URL("file:" + application.getRealPath(xslSourceFilename)).openStream());
      // Generate the transformer.
      javax.xml.transform.Transformer transformer =
                             tFactory.newTransformer(xslSource);
     //   Pass topic to the XSL program.
     transformer.setParameter("topic", topic);   

      // Perform the transformation, sending the output to the response.
      transformer.transform(xmlSource,
                           new javax.xml.transform.stream.StreamResult(out));
    }
    // If an Exception occurs, return the error to the client.
    catch (Exception e)
    {
      out.write("Error: " + e.getMessage());
    }
    // Close the PrintWriter.
    out.close();

%>

h4html.xsl:

<?xml version='1.0'?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xalan="http://xml.apache.org/xslt">
<xsl:output method="html" indent="yes" xalan:omit-meta-tag="yes" />

<!--  parameters passed to XSL:  -->
<xsl:param name="topic" select="''"/>


<!--  '/' matches the document root.  -->
<xsl:template match='/'>
<html>
<head><title>Headline news</title></head>
<body bgcolor="#ffffff" style="font-family:verdana">
   <h3>News Headline</h3>
   News for <xsl:value-of select="$topic" />
   <p />
   <table border="2" cellpadding="5">
      <tr><td style="background-color:#ffffcc">#</td>
          <td style="background-color:#ffffcc">Time</td>
          <td style="background-color:#ffffcc">News</td>
      </tr>
      <xsl:apply-templates select="/news" />
   </table>
</body>
</html>
</xsl:template>

<!--  entry node  -->
<xsl:template match='news'>
   <xsl:for-each select="entry">
      <xsl:sort select="headline" order="ascending"/>
<tr>
         <xsl:choose>
            <xsl:when test='position() mod 2 = 0'>
               <xsl:attribute name='bgcolor'>#ffffff</xsl:attribute>
            </xsl:when>
            <xsl:otherwise>
               <xsl:attribute name='bgcolor'>#ccffff</xsl:attribute>
            </xsl:otherwise>
         </xsl:choose>
   <td><xsl:value-of select="position()" /></td>
   <td><xsl:value-of select="harvesttime" /></td>
        <td><xsl:element name="a" >
            <xsl:attribute name="href"><xsl:value-of select="url" /></xsl:attribute>
         <xsl:value-of select="headline" />
        </xsl:element>
        </td>
</tr>
   </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

h4xml.xsl:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                   version="1.0">

<xsl:output method="xml" version="1.0" indent="yes" />

<!--  parameters passed to XSL:  -->
<xsl:param name="topic" select="''"/>

<xsl:template match='/'>
<news>
    <xsl:attribute name="topic"><xsl:value-of select="$topic" /></xsl:attribute>
    <xsl:for-each select="//entry">
   <xsl:sort select="url/text()" order="ascending" data-type="text" />
   <xsl:if test="not(url/text() = preceding::entry/url/text())">
           <site>
       <xsl:attribute name="url"><xsl:value-of select="url" /></xsl:attribute>
       <xsl:for-each select='//entry[url/text()=current()/url/text()]'>
      <headline><xsl:value-of select="headline" /></headline>
       </xsl:for-each>
           </site>
   </xsl:if>
    </xsl:for-each>
</news>
</xsl:template>
</xsl:stylesheet>