I am parsing a XML using SAXParser and trying to fetch the value for a specific node but my code is returning null. I don't know what am I doing wrong. here is my code. Any help would be greatly appreciated.
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserUsage extends DefaultHandler {
SAXParserFactory factory;
SAXParser parser;
DefaultHandler handler;
private String elementName;
private String authorizationCode;
public String getAuthCodeResponse(String message) throws SAXException, IOException, ParserConfigurationException {
factory = SAXParserFactory.newInstance();
handler = new SAXParserUsage();
parser = factory.newSAXParser();
parser.parse(new InputSource(new StringReader(message)), handler);
return authorizationCode;
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
elementName = qName;
}
public void characters(char[] text, int start, int length) throws SAXException {
if (elementName.equals("code")) {
String code = new String(text, start, length);
System.out.println("setting code: " + code);
authorizationCode = code;
}
}
public void endElement(String arg0, String arg1, String arg2) throws SAXException {
}
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
SAXParserUsage usage = new SAXParserUsage();
String code = usage.getAuthCodeResponse(getSampleString());
System.out.println("code is: " + code);
}
private static String getSampleString() {
String sample = "<washCode><getCode><code>12345</code></getCode></washCode>";
return sample;
}
}
return handler.authorizationCodeNullwhile I am setting value for authorizationCode during parsing