I am using SAX to parse the xml file. I have a tag called image which contains a large base64 string. SAX does not return full string that I need. Here is the SAX Parser that I use.
public class ParseQuestions extends DefaultHandler{
Question question;
private Context context;
public ParseQuestions(Context context){
this.context=context;
}
public List<Question> questions(String filename){
try {
// obtain and configure a SAX based parser
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
// obtain object for SAX parser
SAXParser saxParser = saxParserFactory.newSAXParser();
// default handler for SAX handler class
// all three methods are written in handler's body
DefaultHandler defaultHandler = new DefaultHandler(){
String imageTag="close";
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("image")) {
imageTag = "open";
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
if (imageTag.equals("open")) {
question.setImage(new String(ch, start, length));
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("image")) {
imageTag = "close";
}
};
AssetManager mngr = context.getAssets();
InputStream is = mngr.open(filename);;
saxParser.parse(is, defaultHandler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Any help would be appreciated. Thanks
The characters
method can be called more than once for the text within a single pair of open and close tags.
Your code assumes it's only called once, which will frequently be true for small data, but not always.
You need to initialize a buffer in the startElement method for that tag, collect into the buffer in the characters method, and convert the buffer to a string in the endElement.