Parsing XML from the Net - Using the SAXParser

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Re: Parsing XML from the Net - Using the SAXParser

Postby leeg001 » Thu Jul 29, 2010 11:22 am

Thanks for your tutorial!
I followed your instructions and code as they are.
However, When I ran Android in eclipse, the result is like below!

ExtractedString = nExtractedInt = 1337

There is no value of ExtrarctedString. Why is it?

Thanks in advance.!
leeg001
Once Poster
Once Poster
 
Posts: 1
Joined: Thu Jul 29, 2010 11:14 am

Top

Re: Parsing XML from the Net - Using the SAXParser

Postby stece » Wed Aug 18, 2010 8:19 pm

thank you for this great tutorial :D it helped a lot!
User avatar
stece
Experienced Developer
Experienced Developer
 
Posts: 62
Joined: Wed Apr 21, 2010 10:50 am
Location: Belgium

Re: Parsing XML from the Net - Using the SAXParser

Postby limteckchai » Fri Aug 20, 2010 2:19 am

Hi, thanks for the tutorial...

Did any get the same error as me??? -- when i parse the XML n got data like
<result>
<item>HAPPY</item>
<item>ANDDEV</item>
<item>DAY</item>
<item>LOL & LOL </item>
</result>

for the last item i would get a " LOL" as the result. The '&' and anything before that was not read !!

Thanks in advance.
limteckchai
Experienced Developer
Experienced Developer
 
Posts: 92
Joined: Mon Jun 28, 2010 3:33 am

Re: Parsing XML from the Net - Using the SAXParser

Postby clarkkent » Mon Aug 23, 2010 11:52 am

hi, I have an XML file which contains the path of images. I want to retrieve the images and display them..Can anyone help??
clarkkent
Freshman
Freshman
 
Posts: 2
Joined: Tue Jun 22, 2010 7:08 am

Re: Parsing XML from the Net - Using the SAXParser

Postby clarkkent » Mon Aug 23, 2010 11:58 am

Hi, I have an XML file which contains the path of the images. I want to retrieve and display the images. Can anyone help?
clarkkent
Freshman
Freshman
 
Posts: 2
Joined: Tue Jun 22, 2010 7:08 am

Re: Parsing XML from the Net - Using the SAXParser

Postby alinescoo » Fri Aug 27, 2010 12:37 pm

Very nice tutorial but I can't adapt it to my needs.
I have a REST web service that returns an xml result like this:
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. - <MyCategories xmlns="http://schemas.datacontract.org/2004/07/ceva" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  2. - <Category>
  3.   <CategoryName>First category</CategoryName>
  4.   <Id>1</Id>
  5.   </Category>
  6. - <Category>
  7.   <CategoryName>Second category</CategoryName>
  8.   <Id>2</Id>
  9.   </Category>
  10. - <Category>
  11.   <CategoryName>Third category</CategoryName>
  12.   <Id>3</Id>
  13.   </Category>
  14.   </MyCategories>
  15.  
Parsed in 0.003 seconds, using GeSHi 1.0.8.4


I acces the web service like this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. HttpClient httpclient = new DefaultHttpClient();  
  2.              HttpGet request = new HttpGet(WebServiceURL);  
  3.              request.addHeader("deviceId", deviceId);  
  4.              BasicResponseHandler handler = new BasicResponseHandler();  
  5.              
  6.              result = httpclient.execute(request, handler);
  7.  
Parsed in 0.031 seconds, using GeSHi 1.0.8.4

In result I get the xml response from the web service. I want to be able to use this result and display it in a listview.

How can I achieve this ?
alinescoo
Junior Developer
Junior Developer
 
Posts: 24
Joined: Fri Aug 20, 2010 11:08 am

Top

Re: Parsing XML from the Net - Using the SAXParser

Postby BlakeJ » Sat Sep 04, 2010 6:26 pm

I followed the tutorial exactly, but nothing shows up after Extracted Sting. Any ideas why?
BlakeJ
Junior Developer
Junior Developer
 
Posts: 10
Joined: Sat Sep 04, 2010 8:45 am

Re: Parsing XML from the Net - Using the SAXParser

Postby Hjalte » Sat Sep 11, 2010 6:21 pm

First of all thanks for a great tutorial,

BlakeJ wrote:I followed the tutorial exactly, but nothing shows up after Extracted Sting. Any ideas why?

leeg001 wrote:...I followed your instructions and code as they are.
However, When I ran Android in eclipse, the result is like below!

ExtractedString = nExtractedInt = 1337

There is no value of ExtrarctedString. Why is it? ...


Actually the default result is 2 chars long - they are just not characters you can see, rather spaces.

Due to the format of the XML provided by anddev, the function characters (char ch[], int start, int length) is called four times, and the value stored in "extractedString" using setExtractedString() is overwritten every time - hence you only see the last run containing the 2 spaces.

You can test this by, for example, changing setExtractedString() to increment with extractedString instead of assigning it.

But the problem is solved if you make your own corrected XML file, where the text in <mytag> doesn't end (and start) with spaces.

Perhaps the admin can change the XML file provided as well?

Hope it works out for you

BR
Hjalte
Hjalte
Once Poster
Once Poster
 
Posts: 1
Joined: Sat Sep 11, 2010 6:03 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby davidb » Mon Sep 20, 2010 10:16 am

Hello plusminus,
I have gone through your your example whcih is truely awesome but and done the Parsing following it. The problem is I am getting the OutPut not Parsed and I might know the reason also perhaps but don't k know how to sort it out eventually.
Actually my xml response is quite different than one which is shown in your example.
my XML Response :
<?xml version="1.0" ?>
- <xml_api_reply version="1">
- <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
- <forecast_information>
<city data="Amdavad, Gujarat" />
<postal_code data="Ahmedabad" />
<latitude_e6 data="" />
<longitude_e6 data="" />
<forecast_date data="2010-09-20" />
<current_date_time data="2010-09-20 06:10:00 +0000" />
<unit_system data="US" />
</forecast_information>
- <current_conditions>
<condition data="Smoke" />
<temp_f data="88" />
<temp_c data="31" />
<humidity data="Humidity: 55%" />
<icon data="/ig/images/weather/smoke.gif" />
<wind_condition data="Wind: W at 15 mph" />
</current_conditions>
- <forecast_conditions>
<day_of_week data="Mon" />
<low data="66" />
<high data="93" />
<icon data="/ig/images/weather/cloudy.gif" />
<condition data="Cloudy" />
</forecast_conditions>
- <forecast_conditions>
<day_of_week data="Tue" />
<low data="73" />
<high data="93" />
<icon data="/ig/images/weather/mostly_sunny.gif" />
<condition data="Partly Sunny" />
</forecast_conditions>
- <forecast_conditions>
<day_of_week data="Wed" />
<low data="73" />
<high data="93" />
<icon data="/ig/images/weather/mostly_sunny.gif" />
<condition data="Mostly Sunny" />
</forecast_conditions>
- <forecast_conditions>
<day_of_week data="Thu" />
<low data="73" />
<high data="93" />
<icon data="/ig/images/weather/chance_of_storm.gif" />
<condition data="Chance of Storm" />
</forecast_conditions>
</weather>
</xml_api_reply>
from the above whole response I just want to parse the data "<f_temp data>, <humidity data> and the <icon data> form the TAG :-<current_conditions> only.
My output is : ExtractedString = nullExtractedInt= 0
and the responce in the InputSource is also like this :- Response ====> org.xml.sax.InputSource@43d13808

XmlParser.java
package d.android.parsing;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class XmlParser extends Activity
{

private final String MY_DEBUG_TAG = "WeatherForcaster";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

/* Create a new TextView to display the ParsingResult later */
TextView dt = new TextView(this);
try
{
/* Create a URL we want to load some xml-data from */

URL url = new URL("http://www.google.com/ig/api?weather=Ahmedabad");

/* Create a SAXParser from the SAXParserFactory */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();

/* Get the XMLReader of the SAXParser we created */
XMLReader xmlr = sp.getXMLReader();

/* Create a New ContentHandler and apply it to the XMLReader */
DemoHandler myDemoHandler = new DemoHandler();
xmlr.setContentHandler(myDemoHandler);


/* Now Parse the XML Data from our URL */
xmlr.parse(new InputSource(url.openStream()));

/* The Parsing has been finished */

/* Now our Created Handler "DemoHandler" will provide the Parsed data to Us */
ParsedDemoData parsedDemoData = myDemoHandler.getParsedData();

/* Set the Result to be displayed in our GUI */
dt.setText(parsedDemoData.toString());

}

catch (Exception e)
{
/* Display any Error Message to the GUI */
dt.setText("Error :" + e.getMessage());
Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
}


/* Display the TextView */
this.setContentView(dt);
}



}

DemoHandler.java
package d.android.parsing;

import java.util.jar.Attributes;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class DemoHandler extends DefaultHandler{

private boolean in_xml_api_reply = false;
private boolean in_weather = false;
private boolean in_current_conditions = false;

private ParsedDemoData myParsedDemoData = new ParsedDemoData();


/*
* Getter and Setter
*/

public ParsedDemoData getParsedData() {
return this.myParsedDemoData;
}

/*
* Methods
*/

@Override
public void startDocument() throws SAXException {
this.myParsedDemoData = new ParsedDemoData();
}

@Override
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 nasmespaceURI, String localName, String qName, Attributes atts) throws SAXException
{
//boolean temp_f = false;
if (localName.equals("xml_api_reply"))
{
this.in_xml_api_reply = true;
}
else if(localName.equals("weather"))
{
this.in_weather = true;
}
else if (localName.equals("current_conditions"))
{
this.in_current_conditions = true;
}
else if (localName.equals("temp_f"))
{
// Extract an Attribute
String attrValue = atts.getValue("data");
int i = Integer.parseInt(attrValue);
myParsedDemoData.setExtractedInt(i);
}



}

/** Gets be called on closing tags like:
* </tag> */
@Override
public void endElement(String nasmespaceURI, String localName, String qName) throws SAXException
{
if (localName.equals("xml_api_reply"))
{
this.in_xml_api_reply = false;
}
else if (localName.equals("weather"))
{
this.in_weather = false;
}
else if (localName.equals("current_conditions"))
{
this.in_current_conditions = false;
}
else if (localName.equals("temp_f"))
{

}
}

/** Gets be called on the following structure:
* <tag>characters</tag> */
@Override
public void characters(char ch[], int start, int length)
{
if(this.in_current_conditions)
{
myParsedDemoData.setExtractedString(new String(ch, start, length));
}
}

}

ParsedDemoData.jave
package d.android.parsing;

public class ParsedDemoData
{
private String extractedString = null;
private int extractedInt = 0;

public String getExtractedString() {
return extractedString;
}
public void setExtractedString(String extractedString) {
this.extractedString = extractedString;
}

public int getExtractedInt() {
return extractedInt;
}
public void setExtractedInt(int extractedInt) {
this.extractedInt = extractedInt;
}

public String toString(){
return "ExtractedString = " + this.extractedString
+ "\nExtractedInt = " + this.extractedInt;
}
}

Any help would be greatly appreciated.
Thanks,
davidb
davidb
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Sep 20, 2010 8:31 am

Re:

Postby stelioschar » Wed Oct 06, 2010 10:14 am

Hello padde,

Thanks for your tut.
I tried to run this code and the output is a blank page.
I've split the first part into three separate file-classes, but i don't have any output.

Can you help me?? :roll:

padde wrote:This sample code parse...
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.XMLparser;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.Vector;
  6.  
  7. import javax.xml.parsers.ParserConfigurationException;
  8. import javax.xml.parsers.SAXParser;
  9. import javax.xml.parsers.SAXParserFactory;
  10.  
  11. import org.xml.sax.Attributes;
  12. import org.xml.sax.InputSource;
  13. import org.xml.sax.SAXException;
  14. import org.xml.sax.XMLReader;
  15. import org.xml.sax.helpers.DefaultHandler;
  16.  
  17. import android.app.Activity;
  18. import android.os.Bundle;
  19. import android.widget.TextView;
  20.  
  21. class ParsedExampleDataSet {
  22.     private String schoolname;
  23.     private String studentname;
  24.     private String studentage;
  25.     private String studentaddress;
  26.     private String schooladdress;
  27.  
  28.     public String toString() {
  29.         return "Student's Name: " + studentname + "n" + "Student's Address: "
  30.                 + studentaddress + "n" + "Student's Age: " + studentage
  31.                 + "nn" + "School's Name: " + schoolname + "n"
  32.                 + "School's Address: " + schooladdress;
  33.     }
  34.    
  35.     public String getSchoolName() { return schoolname; }
  36.     public void setSchoolName(String schoolname) { this.schoolname = schoolname; }
  37.     public String getStudentName() { return studentname; }
  38.     public void setStudentName(String studentname) { this.studentname = studentname; }
  39.     public String getStudentAge() { return studentage; }
  40.     public void setStudentAge(String studentage) { this.studentage = studentage; }
  41.     public String getStudentAddress() { return studentaddress; }
  42.     public String getSchoolAddress() { return schooladdress; }
  43.     public void setStudentAddress(String studentaddress) {
  44.         this.studentaddress = studentaddress;
  45.     }
  46.     public void setSchoolAddress(String schooladress) {
  47.         this.schooladdress = schooladress;
  48.     }
  49. }
  50.  
  51. class ContentHandler extends DefaultHandler {
  52.     private enum Tags {
  53.         Test, Name, Age, School, Student, Address, Entry
  54.     }
  55.    
  56.     private boolean in_schoolTag = false;
  57.     private boolean in_studentTag = false;
  58.    
  59.     private ParsedExampleDataSet DataSet;
  60.     private Vector<ParsedExampleDataSet> MyParsedExampleDataSets;
  61.    
  62.    
  63.     public ContentHandler() {
  64.         super();
  65.         this.MyParsedExampleDataSets = new Vector<ParsedExampleDataSet>();
  66.     }
  67.  
  68.     public Vector<ParsedExampleDataSet> getParsedExampleDataSets() {
  69.         return this.MyParsedExampleDataSets;
  70.     }
  71.    
  72.     public void startDocument() throws SAXException { }
  73.     public void endDocument() throws SAXException { }
  74.  
  75.     public void startElement(String n, String l, String q, Attributes a) {
  76.          switch(Tags.valueOf(l)) {
  77.              case School:
  78.                  in_schoolTag = true;
  79.                  break;
  80.              case Student:
  81.                  in_studentTag = true;
  82.                  break;
  83.              case Address:
  84.                  if(in_studentTag)
  85.                      DataSet.setStudentAddress(a.getValue("displayname"));
  86.                  if(in_schoolTag)
  87.                      DataSet.setSchoolAddress(a.getValue("displayname"));
  88.                  break;
  89.              case Age:
  90.                  DataSet.setStudentAge(a.getValue("value"));
  91.                  break;
  92.              case Name:
  93.                  if(in_studentTag)
  94.                      DataSet.setStudentName(a.getValue("displayname"));
  95.                  if(in_schoolTag)
  96.                      DataSet.setSchoolName(a.getValue("displayname"));
  97.                  break;
  98.              case Entry:
  99.                  DataSet = new ParsedExampleDataSet();
  100.                  break;
  101.          }
  102.     }
  103.      
  104.     public void endElement(String n, String l, String q) {
  105.         switch(Tags.valueOf(l)) {
  106.             case School:
  107.                 in_schoolTag = false;
  108.                 break;
  109.             case Student:
  110.                 in_studentTag = false;
  111.                 break;
  112.             case Entry:
  113.                 MyParsedExampleDataSets.add(DataSet);
  114.                 break;
  115.         }
  116.     }
  117.      
  118.     public void characters(char ch[], int start, int length) { }
  119. }
  120.  
  121. public class XMLparserSample extends Activity {
  122.     private TextView myTextView;
  123.    
  124.     public void onCreate(Bundle savedInstanceState) {
  125.         super.onCreate(savedInstanceState);
  126.        
  127.         setContentView(R.layout.main);
  128.        
  129.         Vector<ParsedExampleDataSet> test = read(getResources().openRawResource(R.raw.sample));
  130.        
  131.         String text = "";
  132.         for(int i=0; i < test.size(); i++)
  133.             text += test.get(i).toString()+"n-------------------------n";
  134.        
  135.         myTextView = (TextView) findViewById(R.id.textview);        
  136.         myTextView.setText(text);
  137.     }
  138.    
  139.     public Vector<ParsedExampleDataSet> read(InputStream in) {
  140.         SAXParserFactory spf = SAXParserFactory.newInstance();
  141.         SAXParser sp;
  142.         try {
  143.             sp = spf.newSAXParser();
  144.             XMLReader xr = sp.getXMLReader();
  145.             ContentHandler ch = new ContentHandler();
  146.             xr.setContentHandler(ch);
  147.             xr.parse(new InputSource(in));
  148.             return ch.getParsedExampleDataSets();                
  149.         } catch (ParserConfigurationException e) {
  150.         } catch (SAXException e) {
  151.         } catch (IOException e) {}
  152.         return null;
  153.     }    
  154. }
  155.  
Parsed in 0.053 seconds, using GeSHi 1.0.8.4


...this sample.xml in the res/raw folder...
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0"?>
  2. <Test>
  3.     <Entry>
  4.         <Student>
  5.             <Name displayname = "Jane"/>
  6.             <Address displayname = "ABC"/>
  7.             <Age value = "20"/>
  8.         </Student>
  9.         <School>
  10.             <Name displayname = "NTUST"/>
  11.             <Address displayname = "123"/>
  12.         </School>
  13.     </Entry>
  14.     <Entry>
  15.         <Student>
  16.             <Name displayname = "Jane2"/>
  17.             <Address displayname = "ABCD"/>
  18.             <Age value = "21"/>
  19.         </Student>
  20.         <School>
  21.             <Name displayname = "NTUST2"/>
  22.             <Address displayname = "1234"/>
  23.         </School>
  24.     </Entry>
  25. </Test>
  26.  
Parsed in 0.004 seconds, using GeSHi 1.0.8.4


... and shows the results in the TextView of this main.xml in res/layout
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.    android:orientation="vertical"
  4.    android:layout_width="fill_parent"
  5.    android:layout_height="fill_parent"
  6. >
  7. <TextView  
  8.    android:id="@+id/textview"
  9.    android:layout_width="fill_parent"
  10.    android:layout_height="wrap_content"
  11. />
  12. </LinearLayout>
  13.  
Parsed in 0.002 seconds, using GeSHi 1.0.8.4


Greets
Padde
stelioschar
Junior Developer
Junior Developer
 
Posts: 18
Joined: Thu Aug 19, 2010 9:18 am

Re: Parsing XML from the Net - Using the SAXParser

Postby vijay@agreeya » Wed Nov 03, 2010 8:19 am

hi plusminus,
I have tried the same code given by you.
But its not working as expected.
Instead it gives the warning that parsing XMl Activity not responding. and after sometimes it gives the error that operation timed out.....

please help me if any body has the same issue.
vijay@agreeya
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Nov 03, 2010 8:13 am

Re: Parsing XML from the Net - Using the SAXParser

Postby FrunK » Sun Nov 07, 2010 3:05 am

vijay@agreeya wrote:hi plusminus,
I have tried the same code given by you.
But its not working as expected.
Instead it gives the warning that parsing XMl Activity not responding. and after sometimes it gives the error that operation timed out.....

please help me if any body has the same issue.



Check the AndroidManifest::

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
Parsed in 0.000 seconds, using GeSHi 1.0.8.4
FrunK
Freshman
Freshman
 
Posts: 2
Joined: Sun Nov 07, 2010 2:13 am

Re: Parsing XML from the Net - Using the SAXParser

Postby vijay.ketha » Tue Nov 30, 2010 8:30 am

If you people are using kSoap2 which will give SoapObject as a response, we can do so by setting debug property of HTTPTransportSE object to true before making a call and then get the XML response by using responseDump property of the same object after the call.
HTTPTransportSE httpTransport = new HTTPTransportSE(URL);
httpTransport.debug = true;
httpTransport.call(SOAP_ACTION, envelope);
String XMLString = httpTransport.responseDump;
vijay.ketha
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Nov 30, 2010 7:39 am

Re: Parsing XML from the Net - Using the SAXParser

Postby toobsco42 » Tue Nov 30, 2010 10:00 am

So i have followed you example of how to parse xml from the net

parsing_xml_from_the_net_-_using_the_saxparser-t353.html

All works fine. I was just curious, is the whole example basically just making a REST Android app. And if so, then is it not a good idea to make a rest call in the main thread, but rather as a background service? Because there may be times when the network is low and a REST call is unsuccessful and you dont want to slow down the main thread.

Any help on this subject matter would be greatly appreciated.
toobsco42
Freshman
Freshman
 
Posts: 4
Joined: Sun Feb 07, 2010 2:19 am

Re: Parsing XML from the Net - Using the SAXParser

Postby darth_sidious » Fri Dec 31, 2010 7:20 am

The program worked but I got a lot of white spaces in front of the string. Of course I modified the function to remove them but can someone tell me why the white spaces came there in the first place?
Maybe someone else got this problem and posted about it.. but I didn't read the entire thread as it was too long.
darth_sidious
Freshman
Freshman
 
Posts: 4
Joined: Mon Dec 27, 2010 8:36 am

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 8 guests