Reputation: 167
I need to parse document using SAX parser in java. I was able to print all the node values if I use DefaultHandler class traditionally implementing the startElement, endElement and characters method. How can we access the the previous node value at child node, how can I do that?
My Sample XML is:
<staff>
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff>
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
Based on salary node value, I also want to access the first name. I am confused. How can we do it? My sample Code:
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean bfname = false;
boolean blname = false;
boolean bnname = false;
boolean bsalary = 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;
}
if (qName.equalsIgnoreCase("LASTNAME")) {
blname = true;
}
if (qName.equalsIgnoreCase("NICKNAME")) {
bnname = true;
}
if (qName.equalsIgnoreCase("SALARY")) {
bsalary = 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;
}
if (blname) {
System.out.println("Last Name : " + new String(ch, start, length));
blname = false;
}
if (bnname) {
System.out.println("Nick Name : " + new String(ch, start, length));
bnname = false;
}
if (bsalary) {
//System.out.println("Salary : " + new String(ch, start, length));
String nodeValue=new String(ch, start, length);
if(nodeValue.compareTo("100000")==0)
{
**????I need to store the respective respective first name
in ArrayList**
}
bsalary = false;
}
}
};
Upvotes: 2
Views: 7787
Reputation: 1128
You can use a String variable to store the name as
public void characters(char ch[], int start, int length) throws SAXException {
... Code Here ...
if (bfname) {
employeeName = new String(ch, start, length);
bfname = false;
}
... Code Here ...
}
& use this variable at the end as
public void characters(char ch[], int start, int length) throws SAXException {
... Code Here ...
if (bsalary) {
String nodeValue=new String(ch, start, length);\
if(nodeValue.compareTo("100000")==0)
{
//Use employeeName Here...
}
bsalary = false;
}
... Code Here ...
}
Upvotes: 1
Reputation: 80176
You can't navigate back and forth when using SAX. You should try using DOM. If you have to use SAX then you can use Stack
to hold the previous data and pop them as required.
Upvotes: 3