CSCI 5931A.1
XML Application Development
Spring 2002
Suggested Solution to Final Examination

(1)

(a) For example,

  1. All attribute nodes: //@*.
  2. All person element nodes of persons who have a husband: //person[@gender="F" and link[@spouse]].
  3. All luckynumber attribute notes with values > 4: //@luckynumber[. > 4].
  4. All attribute nodes except the 'father' attribute nodes: //@*[local-name() != 'father'].
  5. The first name of the person with a ssn of '111222333': //person[@ssn='s111222333']/first.

(b) The root element.

(2) For example,

<?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" />

<xsl:template match='/'>
  <xsl:apply-templates />
</xsl:template>

<xsl:template match='*'>
   <xsl:copy>
     <xsl:attribute name="numAttributes"><xsl:value-of select="count(@*)" /></xsl:attribute>
     <xsl:apply-templates />
  </xsl:copy>
</xsl:template>

<xsl:template match='text()|@*' />
</xsl:stylesheet>

(3) For example,

   private static int getElementWithCommentCount(Element element)
   {   //   Whether element contains comments.
      boolean hasTopLevelComments = false;
      int result = 0;

      if (element == null) return 0;

      //  Loop through children nodes to sum up their counts.     
      int i = 0;
      NodeList childNodes = element.getChildNodes();
      int numChildNodes = childNodes.getLength();
      for (i=0; i< numChildNodes; i++)
      {   short nodeType = childNodes.item(i).getNodeType();
         if (nodeType == Node.ELEMENT_NODE) {
            int childElementWithCommentCount = getElementWithCommentCount((Element) childNodes.item(i));
            if (childElementWithCommentCount > 0) {
               result += childElementWithCommentCount;
               hasTopLevelComments = true;
            }
         }
         else {
            if (nodeType == Node.COMMENT_NODE) {
               hasTopLevelComments = true;
            }
         }
      }

      //   Add the current element to the count.
      if (hasTopLevelComments) result++;
      return result;
   }   //   getElementWithCommentCount