CSCI 5733.1
XML Application Development
Spring 2003
Suggested Solution to Mid-Term Examination

(1) For example, a version that accept Element is of course acceptable too.

   private static int numberOfPI(Node root)
   {   if (root == null) return 1;
      switch (root.getNodeType())
      {   case Node.PROCESSING_INSTRUCTION_NODE: return 0;
         case Node.ELEMENT_NODE:
         case Node.DOCUMENT_NODE:
            //   Recursive calls to test for child that is self containing.
            NodeList childNodes = root.getChildNodes();
            int numChildNodes = childNodes.getLength();
            int result = 0;
            for (int i=0; i< numChildNodes; i++)
            {   result += numberOfPI(childNodes.item(i));
            }
            return result;
      }
      return 0;
   }   //   NumberOfPI

(2) (a) For example,

<?xml version="1.0"?>

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:simpleType name="divisibleByTen">
    <xsd:restriction base="xsd:positiveInteger">
      <xsd:pattern value="\d*0"/>
    </xsd:restriction>
  </xsd:simpleType>
  <xsd:element name="a">
    <xsd:complexType>
      <xsd:sequence>
       <xsd:element name="b" type="divisibleByTen" />
       <xsd:element minOccurs="0" maxOccurs="unbounded" name="c" type="divisibleByTen" />
      </xsd:sequence>
      <xsd:attribute name="num" type="divisibleByTen" use="optional" />
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

(b) For example:

<!ELEMENT a (#PCDATA | b | c | d | e)*>
<!ATTLIST a w NMTOKEN #IMPLIED>

(3)

(a) For example:

   //   Number of elements and attributes counted so far.
   private static int numAttributes = 0;
   private static int numElements = 0;

   //   Handler methods
   public void startElement(String namespaceURI,
      String lName,
      String qName,
      Attributes attrs)
      throws SAXException
   {   numElements++;
       numAttributes += attrs.getLength();
   }   //   startElement

   public void endDocument() {
      averageNumAttributes = ((double) numAttributes) / ((double) numElements);
   }   //   endDocument

(b) No. IgnorableWhiteSpace will only called when the parser knows for sure that the white spaces are ignorable, which will require a DTD. This XML file does not have a DOCTYPE.

(c) For example,

use strict;
use CGI;
$|++;

my $q = new CGI;
my $xml = $q->param("input");
my @result = $xml =~ /<b>(.*?)<\/b>/gsi;

print $q->header;
print <<__START;
<html>
<head><title>Mid Term Question</title></head>
<body>
Values of &lt;b&gt;:
<ul>
__START

foreach (@result) {
   print "  <li>$_</li>\n";
}

print "</ul></body></html>\n";
exit 0;