Friday, 19 September 2014

Using SaxParser to get an ID



I'm currently trying to make a java file that can do an export with xml. The only thing I need to actually retrieve is the staff id's and nothing else.If my xml file looks like this:



<? xml version= "1.0" ?>
< company>
< staff id = "22" >
< firstname> kate </firstname >
< lastname> kim </lastname >
< nickname> lolo </nickname >
< salary> 10560</ salary >
</ staff>
< staff>
< firstname> Chelsea </firstname >
< lastname> young</ lastname >
< nickname> cheloung </nickname >
< salary> 200700</ salary >
</ staff>
< staff id = "23" >
< firstname> Dani </firstname >
< lastname> Heil </lastname >
< nickname> Heily </nickname >
< salary> 300000</ salary >
</ staff>
</ company>


and my java code looks like this:



package xmlfunctions;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class saxParser {

public static void main(String argv[]) {

try {

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

DefaultHandler handler = new DefaultHandler() {

boolean bfname = false;


public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {

System.out.println("Start Element :" + qName);

if (qName.equalsIgnoreCase("FIRSTNAME")) {
bfname = true;
}



}

public void endElement(String uri, String localName,
String qName) throws SAXException {

System.out.println("End Element :" + qName);

}

public void characters(char ch[], int start, int length) throws SAXException {

if (bfname) {
System.out.println("First Name : " + new String(ch, start, length));
bfname = false;
}



}

};

saxParser.parse("KatesFile.xml", handler);

} catch (Exception e) {
e.printStackTrace();
}

}

}


How can I change it to get it to display the staff id only? That is all I really want not the other tags. Can anyone help please? I'm very unsure as to how to get the id's on their own.


No comments:

Post a Comment