I've been using the SaxParser.
SaxHandler sample:
Code:
package com.schwenkconsulting.blackping.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ResultHandler extends DefaultHandler
{
private boolean m_bInMessage = false;
private boolean m_bInKey = false;
private String m_sStatus;
private String m_sMessage;
private String m_sKey;
public void startDocument() throws SAXException
{
}
public void endDocument() throws SAXException
{
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException
{
if(localName.equalsIgnoreCase("rsp"))
{
String sStatus = atts.getValue("status");
setStatus(sStatus);
}
else if(localName.equalsIgnoreCase("message"))
{
m_bInMessage = true;
}
else if(localName.equalsIgnoreCase("key"))
{
m_bInKey = true;
}
}
public void characters(char ch[], int start, int length)
{
if(this.m_bInMessage)
{
setMessage(new String(ch, start, length));
}
else if(m_bInKey)
{
setKey(new String(ch, start, length));
}
}
/** Gets be called on closing tags like:
* </tag> */
public void endElement(String namespaceURI, String localName, String qName) throws SAXException
{
if(localName.equalsIgnoreCase("message"))
{
m_bInMessage = false;
}
else if(localName.equalsIgnoreCase("key"))
{
m_bInKey = false;
}
}
public String getStatus()
{
return m_sStatus;
}
public void setStatus(String status)
{
m_sStatus = status;
}
public String getMessage()
{
return m_sMessage;
}
public void setMessage(String message)
{
m_sMessage = message;
}
public String getKey()
{
return m_sKey;
}
public void setKey(String key)
{
m_sKey = key;
}
}
Reading XML From an Input Stream
Code:
public static void parseXML(HttpConnection a_oCon, DefaultHandler a_oSAXHandler) throws IOException, ParserConfigurationException, SAXException
{
InputStream s = null;
StringBuffer sbXMLResult = new StringBuffer();
try
{
s = a_oCon.openInputStream();
int ch;
while ((ch = s.read()) != -1)
{
char cChar = (char) ch;
sbXMLResult.append(cChar);
}
}
finally
{
if (s != null)
s.close();
}
ByteArrayInputStream bs = new ByteArrayInputStream(sbXMLResult.toString().getBytes());
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
saxParser.parse(bs, a_oSAXHandler);
}