import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
public class EmployeeXMLHandler extends DefaultHandler {
private List<EmployeeNode> employees = new ArrayList<EmployeeNode>();
private EmployeeNode currentEmployeeNode; // Used in XML Processing only
public EmployeeXMLHandler() {}
private String characterChunk = "" ;
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// We can not be sure that all character will be passed on single call ..
characterChunk = characterChunk + new String(ch,start,length);
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
characterChunk = "";
if (name.equalsIgnoreCase("res_mesg")) {
// create a new instance of employee
currentEmployeeNode = new EmployeeNode();
for (int len = 0; len < attributes.getLength(); len++) {
currentEmployeeNode.setCategory(attributes.getValue("category"));
}
}
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
if (name.equalsIgnoreCase("res_mesg")) {
employees.add(currentEmployeeNode);
} else if (name.equalsIgnoreCase("res_no")) {
currentEmployeeNode.addResNo(characterChunk);
}
}
public void print(){
Iterator<EmployeeNode> iterator = employees.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
public List<EmployeeNode> getEmployees(){
return this.employees;
}
public void process()throws Exception{
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(this);
reader.parse(new InputSource(new FileInputStream("data.xml")));
print();
}
public static void main(String[] args) throws Exception {
new EmployeeXMLHandler().process();
}
/**
* Same thing here .. why public static list .. ?
* If you want it to be public static you can change it..
*/
} |