Parsing http XML response in JAVA (BlackBerry)
Being foolish/novice enough, I had got stuck in how to parse an XML one receives in form of http response.
I could find many ways where one can parse an XML file – but reading http XML response became a challenge for me. Writing the response to a file and then reading the XML from there was not the ideal way. Being round the bend for quite a while, I was able to get things work.
Here is the code snippet, if anyone wants to refer:
——–
// send http request for XML response via connection object
// input stream http response
InputStream inpStream = connection.openInputStream();
parseStringXML(inpStream);
// Parsing XML using SAX
void parseStringXML(InputStream xmlString){
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser sp = spf.newSAXParser();
Status.show("preparing parse");
sp.parse(xmlString, new Handler());
}
catch (Throwable t) {
Status.show("exception in ParseStringXML");
t.printStackTrace();
}}
// Parse SAX Handler – for getting a particular attribute of a tag
class Handler extends DefaultHandler {
boolean tag = false;
boolean attribute = false;
public void startElement(String nsURI, String strippedName,
String tagName, Attributes attributes)
{
if (tagName.equalsIgnoreCase("tagName")){
title = true;
bookMarksReceivedField = new LabelField(attributes.getValue("attribute"), FOCUSABLE );
}}}
Advertisements