SAX - beg question
843834Mar 18 2003 — edited Mar 20 2003I'm learning how to use SAX to parse xml, and it seems straight-forward to me, but apparently my implementation is off somewhere. Here's the problem:
I'm trying to get the hours and minutes attributes from the length element out of the .xml file (in particular named "the_matrix.xml" for testing purposes). The startElement method in my RunningTimeHandler class never seems to be executed. I thought that as the parser went through the xml file, this method would be excuted each time the parser hit an element
Here's the code that's trying to do it:
main:
public static void main( String[] args )
{
double temp;
SAXParser parser;
SAXParserFactory factory;
RunningTimeHandler rth;
rth = new RunningTimeHandler();
factory = SAXParserFactory.newInstance();
parser = factory.newSAXParser();
parser.parse( "the_matrix.xml", rth );
temp = rth.getRunningTime();
System.out.println("Running Time:\t"+ temp);
}
handler:
private double runningTime;
public void startDocument()
{
System.out.println("Starting doc...");
}
public void startElement(String uri,
String localName,
String qName,
Attributes attributes)
{
String hours;
String minutes;
System.out.println("Start Element:\t"+qName);
runningTime = -1.0;
if ( qName.equalsIgnoreCase("length") )
{
hours = attributes.getValue("hours");
minutes = attributes.getValue("minutes");
runningTime = Double.parseDouble(hours) + ( Double.parseDouble(minutes)/60 );
System.out.println("StartElement: runningTime: "+ runningTime);
}
}//end startElement
public double getRunningTime()
{
System.out.println("please work: "+runningTime);
return runningTime;
}
}//end class
and the xml code looks like this:
<?xml version="1.0" ?>
<movie>
<title>The Matrix</title>
<synopsis>
bla bla bla
</synopsis>
<genre>
Sci-Fi
</genre>
<rating>
R
<ratingfor>Violence</ratingfor>
</rating>
<length hours="2" minutes="10" />
<cast>
<person>
<familyname>Reeves</familyname>
<personalname>Keanu</personalname>
</person>
<person>
<familyname>Weaving</familyname>
<personalname>Hugo</personalname>
</person>
</cast>
</movie>