Android – Simple XML DOM Parser Example for Reading Response From InputStream


Hi,

I am trying to use simple XML DOM Parser for my HTTP response.

Basically I am calling .Net webservice and I need to parse response.

Let me also cover calling the .Net webservice.

Webservice can be called/consumed by may way.
For Example:

Use SOAP call, HTTP Get method, HTTP Post method and many more..

I have one Web service method with Post call structure:

POST /api.asmx/validateCredentials HTTP/1.1
Host: api.mywebsite.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length

username=string&password=string

Now I want to call it from Android HTTP Post method.
I will also need BasicNameValue pair for sending data to web service URL.

I’ll do it like:

try {
	HttpClient httpClient = new DefaultHttpClient();
	HttpContext localContext = new BasicHttpContext();
	HttpPost httpPost = new HttpPost("http://api.mywebsite.com/api.asmx/validateCredentials");

	List<NameValuePair> nvps = new ArrayList<NameValuePair>();

	nvps.add(new BasicNameValuePair("username", username));
	nvps.add(new BasicNameValuePair("password", password));

	httpPost.setEntity(new UrlEncodedFormEntity(nvps));

	HttpResponse response = httpClient.execute(httpPost, localContext);

} catch (Exception e) {
	e.printStackTrace();
}

Now First of all I wanted my response as String.

So I use Buffer reader to read the data from response object.

BufferedReader reader = new BufferedReader(new InputStreamReader(
		response.getEntity().getContent(), "UTF-8"));
StringBuffer responseString = new StringBuffer("");
String line;
while ((line = reader.readLine()) != null) {
	responseString.append(line);
}
System.out.println(responseString.toString());

Now I can see the response in LogCat.
I get the XML response (in String) as follow:

<?xml version="1.0" encoding="utf-8"?>
<returnMessage xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://api.myserver.com/">
	<responseCode>S000</responseCode>
	<message>User Authenticated</message>
	<extendedMessage>
		The user's credentials were valid and is authorized to execute this transaction.
	</extendedMessage>
	<userno xsi:type="xsd:double">211</userno>
</returnMessage>

Here you can see some tags and actually we need those values!!

So I can now use this “String” object to parse the XML.

To parse the XML we have several methods like SAX parser, DOM parser XML pool parser etc.

I heard that SAX parser is best, I had also used that one, But here I will go with Simple DOM parser.

So Instead of getting the response in String as above, I can directly use InputStream for DOM parser.

InputStream in = response.getEntity().getContent();

DocumentBuilder builder = DocumentBuilderFactory.newInstance()
		.newDocumentBuilder();
Document doc = builder.parse(in);
String responseCode = "";
String extendedMessage = "";
if (doc != null) {
	NodeList nl = doc.getElementsByTagName("responseCode");
	if (nl.getLength() > 0) {
		Node node = nl.item(0);
		responseCode = node.getTextContent();
	}
	nl = doc.getElementsByTagName("extendedMessage");
	if (nl.getLength() > 0) {
		Node node = nl.item(0);
		extendedMessage = node.getTextContent();
	}
}
System.out.println(responseCode + " " + extendedMessage);

I hope this post can help some one who wants to get started with Android in just 10 minutes!

Advertisements

4 thoughts on “Android – Simple XML DOM Parser Example for Reading Response From InputStream

  1. Turja Chaudhuri

    I want to build an android application which can scan a newspaper webpage and tell the most important headline….is it possible????how to go about it……..

    Reply
  2. Katlyn

    Hello.This article was really interesting, particularly because I was looking
    for thoughts on this subject last Monday.

    Reply

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s