Reputation: 1033
Am trying to parse a xml file ..and trying to read the employee nodes...
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee id="111">
<firstName>Rakesh</firstName>
<lastName>Mishra</lastName>
<location>Bangalore</location>
<secretary>
<employee id="211">
<firstName>Andy</firstName>
<lastName>Mishra</lastName>
<location>Bangalore</location>
</employee>
</secretary>
</employee>
<employee id="112">
<firstName>John</firstName>
<lastName>Davis</lastName>
<location>Chennai</location>
</employee>
<employee id="113">
<firstName>Rajesh</firstName>
<lastName>Sharma</lastName>
<location>Pune</location>
</employee>
</employees>
And in my handler ..I have the below...
class SaxHandler extends DefaultHandler{
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(qName.equals("employee")){
System.out.print("Its an employee ...and not an Secretary");
/*for(int i=0;i< attributes.getLength();i++){
System.out.print("Attr " +attributes.getQName(i)+ " Value " +attributes.getValue(i));
}*/
System.out.println();
}
}
How can i know if the the employee is a secretary or not
Regards
Upvotes: 1
Views: 434
Reputation: 23637
You need to add another if
inside startElement
to detect the secretary
start element event, and set a flag that you can test when you are inside the employee
tag. Then you reset the flag when you leave the secretary
element. For example
class SaxHandler extends DefaultHandler {
private boolean insideSecretaryTag = false;
@Override
public void startElement(...) throws SAXException {
if(qName.equals("employee")){
if(insideSecretaryTag) {
// this is a secretary
} else {
// not a secretary
}
}
if(qName.equals("secretary")){
insideSecretaryTag = true;
}
public void endElement(...) {
if(qName.equals("secretary")){
insideSecretaryTag = false;
}
}
}
Upvotes: 1