CSCI 5931A.1
XML Application Development
Summer 2002
Suggested Solution to Mid-Term Examination(1) For example,
use strict;
use CGI::Pretty qw(-nosticky);
$|++;
# my $datafile = "t1aq1dat.txt";
my $q = new CGI;
my $path = $q->path_translated();
$path =~ s/\\[^\\]*$/\\/;
my $datafile = "$path\\t1aq1dat.txt";
print $q->header('text/xml');
print <<_XML_HEADER;
<?xml version="1.0" ?>
_XML_HEADER
if (! open(IN, "<$datafile")) {
print "<quotes />";
exit 0 ;
}
print "<quotes>\n";
while ($_ = <IN>) {
chomp;
print " <author>\n" . xmlencode($_) . "\n </author>\n";
print " <quote>\n";
while ($_ = <IN>) {
chomp;
last if !$_;
print xmlencode($_) . "\n";
}
print " </quote>\n";
}
print "</quotes>\n";
close IN;
exit 0;
sub xmlencode {
my $result = shift;
$result =~ s/&/&/g;
$result =~ s/</</g;
$result =~ s/>/>/g;
$result =~ s/"/"/g;
$result =~ s/'/'/g;
$result;
} # xmlencode(2) (a) For example,
<!ELEMENT graph (node*)>
<!ELEMENT node EMPTY>
<!ATTLIST node name ID #REQUIRED
weight CDATA #IMPLIED
To IDREFS #IMPLIED>
(b) (i) <!ELEMENT A (B|C|D)*>
(ii)
<!ELEMENT A ((B|C|D), (B|C|D)?, (B|C|D)?)>
<!ATTLIST A X NMTOKEN #REQUIRED>(iii) <!ELEMENT A ((B) | (B, B) | (B, B, B) | (B, B, C) | (B, B, D) | (B, C) | (B, C, C) | (B, C, D) | (B, D) | (B, D, D) | (C) | (C, C) | (C, C, C) | (C, C, D) | (C, D) | (C, D, D) | (D) | (D, D) | (D, D, D))>
(c) The XML file is valid.
(3) For example:
/* Data members */
/* --------------- */
private int treeDepth = 0; // current tree depth
private int currentDepth = -1;
// depth of current node.
private int maxNumAttributes = 0;
/* Handler methods */
/* --------------- */
public void setDocumentLocator (Locator locator) {
}
public void startDocument()
throws SAXException
{
} // startDocument
public void endDocument()
throws SAXException
{
System.out.println("Depth of tree = " + treeDepth);
System.out.println("Maximum number of attributes in an element = " + maxNumAttributes);
} // endDocument
public void startElement(String namespaceURI,
String lName, // local name
String qName, // qualified name
Attributes attrs)
throws SAXException
{
currentDepth++;
if (currentDepth > treeDepth) treeDepth = currentDepth;
int numAttributes = attrs.getLength();
if (numAttributes > maxNumAttributes) maxNumAttributes = numAttributes;
} // startElement
public void endElement(String namespaceURI,
String lName, // simple name
String qName // qualified name
)
throws SAXException
{
currentDepth--;
} // endElement