CSCI 5931A.1
XML Application Development
Fall 2002
Suggested Solution to Mid-Term Examination(1) For example,
// Number of elements of the tree so far.
private static int numElements = 0;
// Depth of the current element. A null
// tree has a depth of -1.
private static int currentDepth = -1;
// Sum of depth of all elements encountered so far.
private static int totalDepth = 0;
// Handler methods
public void startElement(String namespaceURI,
String lName,
String qName,
Attributes attrs)
throws SAXException
{ currentDepth++;
totalDepth += currentDepth;
numElements++;
} // startElement
public void endElement(String namespaceURI,
String lName,
String qName)
throws SAXException
{ currentDepth--;
} // endElement
public void endDocument()
throws SAXException
{ averageDepth = (double) totalDepth / (double) numElements;
// does not work because of integer division:
// averageDepth = totalDepth / numElements;
} // endDocument(2) (a) For example,
<xsd:simpleType name="EvenNaturalNumber">
<xsd:restriction base="xsd:string">
<xsd:pattern value="2|4|6|8|([1-9][0-9]*[02468])"/>
</xsd:restriction>
</xsd:simpleType>(b) For example:
<!ELEMENT enrollment (students, courses)>
<!ELEMENT students (student*)>
<!ELEMENT student EMPTY>
<!ATTLIST student
id ID #REQUIRED
lastname NMTOKEN #REQUIRED
firstname NMTOKEN #REQUIRED>
<!ELEMENT courses (course*)>
<!ELEMENT course EMPTY>
<!ATTLIST course
id ID #REQUIRED
courseNumber NMTOKEN #REQUIRED
session NMTOKEN #REQUIRED
title NMTOKEN #REQUIRED
students IDREFS #REQUIRED>(c) For example:
use strict;
my $time = localtime;
print <<__END;
Content-type: text/xml
<?xml version="1.0" ?>
<servertime>
The current date & time is $time
</servertime>
__END
exit 0;(3)
(a) For example:
private static void DeleteB (org.w3c.dom.Element element) {
if (element == null) return;
NodeList childNodes = element.getChildNodes();
// for (int i=0; i < childNodes.getLength(); i++) {
// Very subtle error as there may be text nodes between elements
// to hide the errors.
int i=0;
while (i <childNodes.getLength()) {
if (childNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
// An element child node
Element child = (Element) childNodes.item(i);
if ("B".equals(child.getNodeName())) {
element.removeChild(child);
}
else {
DeleteB(child);
i++;
}
} // if
else
i++;
} // while
} // DeleteB(b) For example:
System.out.print(a.getFirstChild().getNodeValue());