I just got out of class where I had my final for Java2. I wasn't able to complete the assignment and it's bugging the heck out of me. Could you all help me figure out what I was doing wrong? The final product should have printed out all the "Students" in the console. I know why I only got the student names, but I could not figure out how to get all of the xml fields to print out. I.E. firstname, lastname, age. I thought it should be...
public void startElement(String namespaceURI, String localName, String var, Attributes atts){
if (var.equalsIgnoreCase("student")){
write = true;
}else{
write = false;
}
...in the reader, but then I get nothing under the header. Where did I go wrong?
Thanks,
Jonboy
package Final;
import org.apache.xerces.parsers.SAXParser;
public class FinalTester {
public static void main(String[] args){
//System.out.println("Before FinalReader");
FinalReader xmlReader = new FinalReader();
//SaxReader xmlReader = new SaxReader();
SAXParser parser = new SAXParser();
parser.setContentHandler(xmlReader);
System.out.println("First Name Last Name Age");
try{
parser.parse("final.xml");
}catch(Exception ex){
ex.printStackTrace();
}
}
}
package Final;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class FinalReader extends DefaultHandler{
boolean write = false;
public void startElement(String namespaceURI, String localName, String var, Attributes atts){
if (var.equalsIgnoreCase("firstname")){
write = true;
}else{
write = false;
}
}
final public void characters( final char[] ch, final int start, final int len) {
final String text = new String(ch, start, len);
final String text1 = text.trim();
if(text1.length()>0 && write)
System.out.println(text1);
}
}
Here is the XML we were to read...
<class>
<student><firstname>Joe</firstname><lastname>Josh</lastname><age>19</age>
</student>
<student><firstname>Mary</firstname><lastname>Lamb</lastname><age>24</age>
</student>
<student><firstname>Jack</firstname><lastname>BeNimble</lastname><age>22</age>
</student>
<student><firstname>Martha</firstname><lastname>Stewart</lastname><age>67</age>
</student>
<student><firstname>Fat</firstname><lastname>Albert</lastname><age>18</age>
</student>
</class>