Parsing XML from the Net - Using the SAXParser

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

Parsing XML from the Net - Using the SAXParser

Postby plusminus » Sat Dec 22, 2007 6:12 pm

Parsing XML from the Net - Using the SAXParser


What you learn: You will learn how to properly parse XML (here: from the net) using a SAXParser.

:?: Problems/Questions: Write them right below...

Difficulty: 1 of 5 :)

What it will look like:
Image


Description:
0.) In this tutorial we are going to parse the following XML-File located at the following url: images/tut/basic/parsingxml/example.xml :
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0"?>
  2. <outertag>
  3.         <innertag sampleattribute="innertagAttribute">
  4.                 <mytag>
  5.                         anddev.org rulez =)
  6.                 </mytag>
  7.                 <tagwithnumber thenumber="1337"/>
  8.         </innertag>
  9. </outertag>
Parsed in 0.001 seconds, using GeSHi 1.0.8.4


To accomplish the parsing, we are going to use a SAX-Parser (Wiki-Info). SAX stands for "Simple API for XML", so it is perfect for us :)

1.) Lets take a look at the onCreate(...)-method. It will open an URL, create a SAXParser, add a ContentHandler to it, parse the URL and display the Results in a TextView.
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         /** Called when the activity is first created. */
  2.         @Override
  3.         public void onCreate(Bundle icicle) {
  4.                 super.onCreate(icicle);
  5.  
  6.                 /* Create a new TextView to display the parsingresult later. */
  7.                 TextView tv = new TextView(this);
  8.                 try {
  9.                         /* Create a URL we want to load some xml-data from. */
  10.                         URL url = new URL("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");
  11.  
  12.                         /* Get a SAXParser from the SAXPArserFactory. */
  13.                         SAXParserFactory spf = SAXParserFactory.newInstance();
  14.                         SAXParser sp = spf.newSAXParser();
  15.  
  16.                         /* Get the XMLReader of the SAXParser we created. */
  17.                         XMLReader xr = sp.getXMLReader();
  18.                         /* Create a new ContentHandler and apply it to the XML-Reader*/
  19.                         ExampleHandler myExampleHandler = new ExampleHandler();
  20.                         xr.setContentHandler(myExampleHandler);
  21.                        
  22.                         /* Parse the xml-data from our URL. */
  23.                         xr.parse(new InputSource(url.openStream()));
  24.                         /* Parsing has finished. */
  25.  
  26.                         /* Our ExampleHandler now provides the parsed data to us. */
  27.                         ParsedExampleDataSet parsedExampleDataSet =
  28.                                                                         myExampleHandler.getParsedData();
  29.  
  30.                         /* Set the result to be displayed in our GUI. */
  31.                         tv.setText(parsedExampleDataSet.toString());
  32.                        
  33.                 } catch (Exception e) {
  34.                         /* Display any Error to the GUI. */
  35.                         tv.setText("Error: " + e.getMessage());
  36.                         Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
  37.                 }
  38.                 /* Display the TextView. */
  39.                 this.setContentView(tv);
  40.         }
Parsed in 0.034 seconds, using GeSHi 1.0.8.4


2.) The next Class to take a look at is the ExampleHandler which extends org.xml.sax.helpers.DefaultHandler. A SAX-Handler is an really easy class. We will just need to implement some trivial functions.
The SAXParser will 'walk' through the XML-File from the beginning to the end and always, when it reaches an opening tag like:
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <outertag>
Parsed in 0.000 seconds, using GeSHi 1.0.8.4

the Handler-Function:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         @Override
  2.         public void startElement(String namespaceURI, String localName,
  3.                         String qName, Attributes atts) throws SAXException {
  4.         }
Parsed in 0.030 seconds, using GeSHi 1.0.8.4

gets called. Where in this case localName will be "outertag".
The same happens on closing tags, like:
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. </outertag>
Parsed in 0.000 seconds, using GeSHi 1.0.8.4

Here the equivalent 'closing'-method that gets called:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         @Override
  2.         public void endElement(String namespaceURI, String localName, String qName)
  3.                         throws SAXException {
  4.         }
Parsed in 0.034 seconds, using GeSHi 1.0.8.4

In XML you can put any characters you want between a opening and an closing tag, like this:
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.                 <mytag>
  2.                         anddev.org rulez =)
  3.                 </mytag>
Parsed in 0.001 seconds, using GeSHi 1.0.8.4

When the Parser reaches such a Tag, the following method gets called, providing the characters between the opening and the closing tag:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         /** Gets be called on the following structure:
  2.          * <tag>characters</tag> */
  3.         @Override
  4.     public void characters(char ch[], int start, int length) {
  5.                 String textBetween = new String(ch, start, length);
  6.     }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


Finally on the start/end of each document the following functions get called:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         @Override
  2.         public void startDocument() throws SAXException {
  3.                 // Do some startup if needed
  4.         }
  5.  
  6.         @Override
  7.         public void endDocument() throws SAXException {
  8.                 // Do some finishing work if needed
  9.         }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


3.) What was shown up to here was just the basic structure of the SAX-Handler. Now I'll show you the standard way of a real-life Handler-Implementation. This is also pretty simple. We probably want to know how 'deep' the Parser has parsed so far, so we create some booleans indicating which tags are still open. This is done like the following:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         // ===========================================================
  2.         // Fields
  3.         // ===========================================================
  4.        
  5.         private boolean in_outertag = false;
  6.         private boolean in_innertag = false;
  7.         private boolean in_mytag = false;
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


As we know, when the parser reaches an opening-tag the startElement(...)-method gets called:
So we will simply check the localName and set the corresponding "in_xyz"-boolean to true.
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         @Override
  2.         public void startElement(String namespaceURI, String localName,
  3.                         String qName, Attributes atts) throws SAXException {
  4.                 if (localName.equals("outertag")) {
  5.                         this.in_outertag = true;
  6.                 }else if (localName.equals("innertag")) {
  7.                         this.in_innertag = true;
  8.                 }else if (localName.equals("mytag")) {
  9.                         this.in_mytag = true;
  10.                 }else if (localName.equals("tagwithnumber")) {
  11.                         String attrValue = atts.getValue("thenumber");
  12.                         int i = Integer.parseInt(attrValue);
  13.                         myParsedExampleDataSet.setExtractedInt(i);
  14.                 }
  15.         }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


Similiar on closing tags the endElement(..)-method gets called and we just set the "in_xyz"-boolean back to false:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         @Override
  2.         public void endElement(String namespaceURI, String localName, String qName)
  3.                         throws SAXException {
  4.                 if (localName.equals("outertag")) {
  5.                         this.in_outertag = false;
  6.                 }else if (localName.equals("innertag")) {
  7.                         this.in_innertag = false;
  8.                 }else if (localName.equals("mytag")) {
  9.                         this.in_mytag = false;
  10.                 }else if (localName.equals("tagwithnumber")) {
  11.                         // Nothing to do here
  12.                 }
  13.         }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


So for example when the Parser reaches the following part:

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.                 <mytag>
  2.                         anddev.org rulez =)
  3.                 </mytag>
Parsed in 0.000 seconds, using GeSHi 1.0.8.4

Our "in_xyz"-booleans indicate in which tag these characters have been 'detected' and easily extract them:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         /** Gets be called on the following structure:
  2.          * <tag>characters</tag> */
  3.         @Override
  4.     public void characters(char ch[], int start, int length) {
  5.                 if(this.in_mytag){
  6.                 myParsedExampleDataSet.setExtractedString(new String(ch, start, length));
  7.         }
  8.     }
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


4.) What I prefer is to make the Handler create a nice object that gets created during the whole parsing and when parsing has finished I can simply grab the created Object:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         public ParsedExampleDataSet getParsedData() {
  2.                 return this.myParsedExampleDataSet;
  3.         }
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


So now you know how to properly use the SAXParser together with the SAXHandler :)
If any question remained feel free to ask :!:


The Full Source:

"/src/your_package_structure/ParsingXML.java"
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.parsingxml;
  2.  
  3. import java.net.URL;
  4.  
  5. import javax.xml.parsers.SAXParser;
  6. import javax.xml.parsers.SAXParserFactory;
  7.  
  8. import org.xml.sax.InputSource;
  9. import org.xml.sax.XMLReader;
  10.  
  11. import android.app.Activity;
  12. import android.os.Bundle;
  13. import android.util.Log;
  14. import android.widget.TextView;
  15.  
  16. public class ParsingXML extends Activity {
  17.        
  18.         private final String MY_DEBUG_TAG = "WeatherForcaster";
  19.  
  20.         /** Called when the activity is first created. */
  21.         @Override
  22.         public void onCreate(Bundle icicle) {
  23.                 super.onCreate(icicle);
  24.  
  25.                 /* Create a new TextView to display the parsingresult later. */
  26.                 TextView tv = new TextView(this);
  27.                 try {
  28.                         /* Create a URL we want to load some xml-data from. */
  29.                         URL url = new URL("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");
  30.  
  31.                         /* Get a SAXParser from the SAXPArserFactory. */
  32.                         SAXParserFactory spf = SAXParserFactory.newInstance();
  33.                         SAXParser sp = spf.newSAXParser();
  34.  
  35.                         /* Get the XMLReader of the SAXParser we created. */
  36.                         XMLReader xr = sp.getXMLReader();
  37.                         /* Create a new ContentHandler and apply it to the XML-Reader*/
  38.                         ExampleHandler myExampleHandler = new ExampleHandler();
  39.                         xr.setContentHandler(myExampleHandler);
  40.                        
  41.                         /* Parse the xml-data from our URL. */
  42.                         xr.parse(new InputSource(url.openStream()));
  43.                         /* Parsing has finished. */
  44.  
  45.                         /* Our ExampleHandler now provides the parsed data to us. */
  46.                         ParsedExampleDataSet parsedExampleDataSet =
  47.                                                                         myExampleHandler.getParsedData();
  48.  
  49.                         /* Set the result to be displayed in our GUI. */
  50.                         tv.setText(parsedExampleDataSet.toString());
  51.                        
  52.                 } catch (Exception e) {
  53.                         /* Display any Error to the GUI. */
  54.                         tv.setText("Error: " + e.getMessage());
  55.                         Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
  56.                 }
  57.                 /* Display the TextView. */
  58.                 this.setContentView(tv);
  59.         }
  60. }
Parsed in 0.043 seconds, using GeSHi 1.0.8.4


"/src/your_package_structure/ExampleHandler.java"
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.parsingxml;
  2.  
  3. import org.xml.sax.Attributes;
  4. import org.xml.sax.SAXException;
  5. import org.xml.sax.helpers.DefaultHandler;
  6.  
  7.  
  8. public class ExampleHandler extends DefaultHandler{
  9.  
  10.         // ===========================================================
  11.         // Fields
  12.         // ===========================================================
  13.        
  14.         private boolean in_outertag = false;
  15.         private boolean in_innertag = false;
  16.         private boolean in_mytag = false;
  17.        
  18.         private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
  19.  
  20.         // ===========================================================
  21.         // Getter & Setter
  22.         // ===========================================================
  23.  
  24.         public ParsedExampleDataSet getParsedData() {
  25.                 return this.myParsedExampleDataSet;
  26.         }
  27.  
  28.         // ===========================================================
  29.         // Methods
  30.         // ===========================================================
  31.         @Override
  32.         public void startDocument() throws SAXException {
  33.                 this.myParsedExampleDataSet = new ParsedExampleDataSet();
  34.         }
  35.  
  36.         @Override
  37.         public void endDocument() throws SAXException {
  38.                 // Nothing to do
  39.         }
  40.  
  41.         /** Gets be called on opening tags like:
  42.          * <tag>
  43.          * Can provide attribute(s), when xml was like:
  44.          * <tag attribute="attributeValue">*/
  45.         @Override
  46.         public void startElement(String namespaceURI, String localName,
  47.                         String qName, Attributes atts) throws SAXException {
  48.                 if (localName.equals("outertag")) {
  49.                         this.in_outertag = true;
  50.                 }else if (localName.equals("innertag")) {
  51.                         this.in_innertag = true;
  52.                 }else if (localName.equals("mytag")) {
  53.                         this.in_mytag = true;
  54.                 }else if (localName.equals("tagwithnumber")) {
  55.                         // Extract an Attribute
  56.                         String attrValue = atts.getValue("thenumber");
  57.                         int i = Integer.parseInt(attrValue);
  58.                         myParsedExampleDataSet.setExtractedInt(i);
  59.                 }
  60.         }
  61.        
  62.         /** Gets be called on closing tags like:
  63.          * </tag> */
  64.         @Override
  65.         public void endElement(String namespaceURI, String localName, String qName)
  66.                         throws SAXException {
  67.                 if (localName.equals("outertag")) {
  68.                         this.in_outertag = false;
  69.                 }else if (localName.equals("innertag")) {
  70.                         this.in_innertag = false;
  71.                 }else if (localName.equals("mytag")) {
  72.                         this.in_mytag = false;
  73.                 }else if (localName.equals("tagwithnumber")) {
  74.                         // Nothing to do here
  75.                 }
  76.         }
  77.        
  78.         /** Gets be called on the following structure:
  79.          * <tag>characters</tag> */
  80.         @Override
  81.     public void characters(char ch[], int start, int length) {
  82.                 if(this.in_mytag){
  83.                 myParsedExampleDataSet.setExtractedString(new String(ch, start, length));
  84.         }
  85.     }
  86. }
Parsed in 0.046 seconds, using GeSHi 1.0.8.4


"/src/your_package_structure/ParsedExampleDataSet.java"
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.parsingxml;
  2.  
  3. public class ParsedExampleDataSet {
  4.         private String extractedString = null;
  5.         private int extractedInt = 0;
  6.  
  7.         public String getExtractedString() {
  8.                 return extractedString;
  9.         }
  10.         public void setExtractedString(String extractedString) {
  11.                 this.extractedString = extractedString;
  12.         }
  13.  
  14.         public int getExtractedInt() {
  15.                 return extractedInt;
  16.         }
  17.         public void setExtractedInt(int extractedInt) {
  18.                 this.extractedInt = extractedInt;
  19.         }
  20.        
  21.         public String toString(){
  22.                 return "ExtractedString = " + this.extractedString
  23.                                 + "nExtractedInt = " + this.extractedInt;
  24.         }
  25. }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


Thats it :)


Regards,
plusminus
Last edited by plusminus on Sun Jan 06, 2008 6:34 pm, edited 1 time in total.
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Top

Postby Katharnavas » Mon Dec 24, 2007 11:29 am

Hi,
Nice one got the output as stated above.. Looking for more ! :D
Katharnavas
Senior Developer
Senior Developer
 
Posts: 100
Joined: Tue Dec 04, 2007 5:57 am
Location: India

u r an amazing teacher !!

Postby csagar » Sun Jan 06, 2008 4:23 pm

You are a best teacher plusminus!! The way you explain the things is so simple !! thanx dude for the tutorial :)
csagar
Junior Developer
Junior Developer
 
Posts: 15
Joined: Sun Jan 06, 2008 1:42 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby androidbeginner » Wed Feb 06, 2008 7:13 am

hi plusminus..
the following code is written in similar lines to the one on this site..But my code is returning null values for the parameters homephone,workphone and mobile phone...and moreover iam able to read only half the info..
plss help..its very urgent!!!!
XML file:

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="ISO-8859-1" ?>
  2. - <!--  Edited with XML Spy v4.2
  3.  -->
  4. - <Phonebook>
  5. - <PhonebookEntry>
  6.   <firstname>John</firstname>
  7.   <lastname>Connor</lastname>
  8.   <Address>5,Downing Street</Address>
  9.   <Phone loc="home">9875674567</Phone>
  10.   <Phone loc="work">9875674567</Phone>
  11.   <Phone loc="mobile">78654562341</Phone>
  12.   </PhonebookEntry>
  13. - <PhonebookEntry>
  14.   <firstname>Peter</firstname>
  15.   <lastname>Roche</lastname>
  16.   <Address>6,Downing Street</Address>
  17.   <Phone loc="home">7814567890</Phone>
  18.   <Phone loc="work">76890556783</Phone>
  19.   <Phone loc="mobile">4562227890</Phone>
  20.   </PhonebookEntry>
  21.   </Phonebook>
Parsed in 0.005 seconds, using GeSHi 1.0.8.4


Here is the code:
parsingxml.java:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.parsingxml;
  2.  
  3. import java.net.Proxy;
  4. import java.net.Socket;
  5. import java.net.SocketAddress;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8.  
  9. import javax.xml.parsers.SAXParser;
  10. import javax.xml.parsers.SAXParserFactory;
  11.  
  12. import org.xml.sax.InputSource;
  13. import org.xml.sax.XMLReader;
  14.  
  15. import android.app.Activity;
  16. import android.os.Bundle;
  17. import android.util.Log;
  18. import android.widget.TextView;
  19. public class ParsingXML extends Activity {
  20.    
  21.    
  22.    
  23.     /** Called when the activity is first created. */
  24.     @Override
  25.     public void onCreate(Bundle icicle) {
  26.          super.onCreate(icicle);
  27.          System.setProperty("http.proxyHost"," 129.188.69.100 ");
  28.          System.setProperty("http.proxyPort","1080");
  29.          System.setProperty("http.nonProxyHosts","10.228.97.76");
  30.  
  31.          /* Create a new TextView to display the parsingresult later. */
  32.          TextView tv = new TextView(this);
  33.          try {
  34.               /* Create a URL we want to load some xml-data from. */
  35.               URL url = new URL("http://10.232.169.99:8080/phone.xml");
  36.                            URLConnection ucon = url.openConnection();
  37.               /* Get a SAXParser from the SAXPArserFactory. */
  38.               SAXParserFactory spf = SAXParserFactory.newInstance();
  39.               SAXParser sp = spf.newSAXParser();
  40.  
  41.               /* Get the XMLReader of the SAXParser we created. */
  42.               XMLReader xr = sp.getXMLReader();
  43.               /* Create a new ContentHandler and apply it to the XML-Reader*/
  44.               ExampleHandler myExampleHandler = new ExampleHandler();
  45.               xr.setContentHandler(myExampleHandler);
  46.              
  47.               /* Parse the xml-data from our URL. */
  48.               xr.parse(new InputSource(url.openStream()));
  49.               /* Parsing has finished. */
  50.  
  51.               /* Our ExampleHandler now provides the parsed data to us. */
  52.               ParsedExampleDataSet parsedExampleDataSet =
  53.                                             myExampleHandler.getParsedData();
  54.  
  55.               /* Set the result to be displayed in our GUI. */
  56.               tv.setText(parsedExampleDataSet.toString());
  57.              
  58.          } catch (Exception e) {
  59.               /* Display any Error to the GUI. */
  60.               tv.setText("Error: " + e.getMessage());
  61.              
  62.          }
  63.          /* Display the TextView. */
  64.          this.setContentView(tv);
  65.     }
  66. }
Parsed in 0.046 seconds, using GeSHi 1.0.8.4


ParsedExampleDataSet.java

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.parsingxml;
  2.  
  3. public class ParsedExampleDataSet {
  4.     private String firstname = null;
  5.     private String lastname=null;
  6.     private String Address=null;
  7.     private String Phone=null;
  8.     private String homephone=null;
  9.     private String workphone=null;
  10.     private String mobilephone=null;
  11.  
  12.     public String getfirstname() {
  13.          return firstname;
  14.     }
  15.     public void setfirstname(String firstname) {
  16.          this.firstname = firstname;
  17.     }
  18.     public String getlastname(){
  19.         return lastname;
  20.        
  21.     }
  22.     public void setlastname(String lastname){
  23.         this.lastname=lastname;
  24.     }
  25.     public String getAddress(){
  26.         return Address;
  27.     }
  28. public void setAddress(String Address){
  29.         this.Address=Address;
  30. }
  31.     public String getPhone(){
  32.         return Phone;
  33.     }
  34.     public void sethomePhone(String homePhone){
  35.         this.homephone=homePhone;
  36.     }
  37.     public void setworkPhone(String homePhone){
  38.         this.homephone=homePhone;
  39.     }
  40.     public void setmobilePhone(String homePhone){
  41.         this.homephone=homePhone;
  42.     }
  43.        
  44.    
  45.     public String toString(){
  46.          return "firstname = " + this.firstname + "n" + "lastname=" + this.lastname + "n" + "Address=" + this.Address+ "n"  + "homephone=" + this.homephone + "n" + "workphone=" + this.workphone + "n" + "mobilephone=" + this.mobilephone;
  47.                    
  48.     }
  49. }
Parsed in 0.042 seconds, using GeSHi 1.0.8.4


ExampleHandler.java:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.parsingxml;
  2.  
  3. import org.xml.sax.Attributes;
  4. import org.xml.sax.SAXException;
  5. import org.xml.sax.helpers.DefaultHandler;
  6.  
  7.  
  8. public class ExampleHandler extends DefaultHandler{
  9.  
  10.      // ===========================================================
  11.      // Fields
  12.      // ===========================================================
  13.      
  14.      private boolean in_outertag = false;
  15.      private boolean in_innertag = false;
  16.      private boolean in_firstname = false;
  17.      private boolean in_lastname= false;
  18.      private boolean in_Address=false;
  19.      private boolean in_Phone=false;
  20.      private boolean in_homePhone=false;
  21.      private boolean in_workPhone=false;
  22.      private boolean in_mobilePhone=false;
  23.      
  24.      
  25.      private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
  26.  
  27.      // ===========================================================
  28.      // Getter & Setter
  29.      // ===========================================================
  30.  
  31.      public ParsedExampleDataSet getParsedData() {
  32.           return this.myParsedExampleDataSet;
  33.      }
  34.  
  35.      // ===========================================================
  36.      // Methods
  37.      // ===========================================================
  38.      @Override
  39.      public void startDocument() throws SAXException {
  40.           this.myParsedExampleDataSet = new ParsedExampleDataSet();
  41.      }
  42.  
  43.      @Override
  44.      public void endDocument() throws SAXException {
  45.           // Nothing to do
  46.      }
  47.  
  48.      /** Gets be called on opening tags like:
  49.       * <tag>
  50.       * Can provide attribute(s), when xml was like:
  51.       * <tag attribute="attributeValue">*/
  52.      @Override
  53.      public void startElement(String namespaceURI, String localName,
  54.                String qName, Attributes atts) throws SAXException {
  55.           if (localName.equals("PhoneBook")) {
  56.                this.in_outertag = true;
  57.           }else if (localName.equals("PhonebookEntry")) {
  58.                this.in_innertag = true;
  59.           }else if (localName.equals("firstname")) {
  60.                this.in_firstname = true;
  61.           }else if (localName.equals("lastname"))  {
  62.                   this.in_lastname= true;
  63.           }else if(localName.equals("Address"))  {
  64.                   this.in_Address= true;
  65.           }else if (localName.equals("Phone")){
  66.                  String phoneattr=atts.getValue("loc");
  67.                 if(phoneattr.equals("home")){
  68.                 this.in_homePhone=true;}
  69.           }else if (localName.equals("Phone")){
  70.                   String phoneattr=atts.getValue("loc");
  71.                 if(phoneattr.equals("work")){
  72.                  this.in_workPhone=true;}
  73.          }else if (localName.equals("Phone")){
  74.                  String phoneattr=atts.getValue("loc");
  75.                  if(phoneattr.equals("mobile")){
  76.                   this.in_mobilePhone=true;
  77.               }
  78.                           }      
  79.           }
  80.                  
  81.                   //else if (localName.equals("tagwithnumber")) {
  82.          // }
  83.                // Extract an Attribute
  84.               // String attrValue = atts.getValue("thenumber");
  85.               // int i = Integer.parseInt(attrValue);
  86.               // myParsedExampleDataSet.setExtractedInt(i);
  87.         //  }
  88.      
  89.      
  90.      /** Gets be called on closing tags like:
  91.       * </tag> */
  92.      @Override
  93.      public void endElement(String namespaceURI, String localName, String qName)
  94.                throws SAXException {
  95.           if (localName.equals("Phonebook")) {
  96.                this.in_outertag = false;
  97.           }else if (localName.equals("PhonebookEntry")) {
  98.                this.in_innertag = false;
  99.           }else if (localName.equals("firstname")) {
  100.                this.in_firstname = false;
  101.           }else if (localName.equals("lastname"))  {
  102.                   this.in_lastname= false;
  103.           }else if(localName.equals("Address"))  {
  104.                   this.in_Address= false;
  105.           }else if(localName.equals("Phone"))   {
  106.                   this.in_Phone=false;
  107.           }
  108.      }
  109.      
  110.      /** Gets be called on the following structure:
  111.       * <tag>characters</tag> */
  112.      @Override
  113.     public void characters(char ch[], int start, int length) {
  114.           if(this.in_firstname){
  115.           myParsedExampleDataSet.setfirstname(new String(ch, start, length));
  116.           }
  117.           if(this.in_lastname){
  118.           myParsedExampleDataSet.setlastname(new String(ch, start, length));
  119.           }
  120.           if(this.in_Address){
  121.                   myParsedExampleDataSet.setAddress(new String(ch, start, length));
  122.           }
  123.           if(this.in_homePhone){
  124.                   myParsedExampleDataSet.sethomePhone(new String(ch, start, length));
  125.           }
  126.           if(this.in_workPhone){
  127.                   myParsedExampleDataSet.setworkPhone(new String(ch, start, length));
  128.           }
  129.           if(this.in_mobilePhone){
  130.                   myParsedExampleDataSet.setmobilePhone(new String(ch, start, length));
  131.           }
  132.     }
  133. }
Parsed in 0.057 seconds, using GeSHi 1.0.8.4
androidbeginner
Junior Developer
Junior Developer
 
Posts: 17
Joined: Tue Feb 05, 2008 7:10 am

Postby plusminus » Wed Feb 06, 2008 5:05 pm

Hello androidbeginner,

in startelement you have the following:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.           }else if (localName.equals("Phone")){
  2.  
  3.            String phoneattr=atts.getValue("loc");
  4.  
  5.                if(phoneattr.equals("home")){
  6.  
  7.                this.in_homePhone=true;}
  8.  
  9.           }else if (localName.equals("Phone")){
  10.  
  11.             String phoneattr=atts.getValue("loc");
  12.  
  13.                if(phoneattr.equals("work")){
  14.  
  15.                 this.in_workPhone=true;}
  16.  
  17.          }else if (localName.equals("Phone")){
  18.  
  19.            String phoneattr=atts.getValue("loc");
  20.  
  21.                 if(phoneattr.equals("mobile")){
  22.  
  23.                  this.in_mobilePhone=true;
  24.  
  25.               }
  26.  
  27.          }    
Parsed in 0.038 seconds, using GeSHi 1.0.8.4

This won't work, because if one if-case is true, the rest is checked no more :!:
:arrow: here the two lower ones never get checked.
So change it to:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.           }else if (localName.equals("Phone")){
  2.  
  3.            String phoneattr=atts.getValue("loc");
  4.  
  5.                if(phoneattr.equals("home")){
  6.  
  7.                  this.in_homePhone=true;
  8.  
  9.                }else if(phoneattr.equals("work")){
  10.  
  11.                  this.in_workPhone=true;
  12.  
  13.                }else if(phoneattr.equals("mobile")){
  14.  
  15.                  this.in_mobilePhone=true;
  16.  
  17.               }
  18.  
  19.          }    
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Let me know if this already fixed it or if there is sth. more to do. (my time is currently very limited !)

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Vamsi

Postby gvkreddyvamsi » Thu Feb 14, 2008 12:32 pm

Hi ,


IN Parsing application i cann't resolve R.java ..
Plz post .zip file for this application

by
vamsi
gvkreddyvamsi
Developer
Developer
 
Posts: 43
Joined: Mon Jan 21, 2008 5:10 am
Location: INDIA

Top

Re: Vamsi

Postby plusminus » Thu Feb 14, 2008 12:48 pm

Hello vamsi,

R.java is an auto-generated file. That contains the ids of you resources.
It will appear by itself if your project is well configured.
Files should be in the same package as R.java otherwise you need to import it.

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby Ant1 » Mon Feb 18, 2008 12:29 am

Hello PlusMinus I love the site and the tutorials have been really helpful especially this one but I have one question? I'm not sure if it is the same as the above question but I'll ask anyway I have a xml file on the net I want to parse but it has multiple occurrences of the same tag here is the some of the xml file:

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <frbny:Key>
  2.  
  3. <frbny:FREQ>D</frbny:FREQ>
  4.  
  5. <frbny:CURR>AUD</frbny:CURR>
  6.  
  7. <frbny:FX_TIME>12</frbny:FX_TIME>
  8.  
  9. <frbny:FX_TYPE>S</frbny:FX_TYPE>
  10.  
  11. </frbny:Key>
  12.  
  13.  
  14.         <frbny:Obs OBS_STATUS="A" OBS_CONF="F">
  15.  
  16. <frbny:TIME_PERIOD>2008-02-15</frbny:TIME_PERIOD>
  17.  
  18. <frbny:OBS_VALUE>0.9069</frbny:OBS_VALUE>
  19.  
  20. </frbny:Obs>
Parsed in 0.003 seconds, using GeSHi 1.0.8.4


there are 22 more of these to parse in the xml file obviously they all have different values in the CURR and the OBS_VALUE entries and thats what I want to get at. Here is my android code:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public class ExampleHandler extends DefaultHandler {
  3.  
  4.        
  5.  
  6.        
  7.  
  8.         //test tags see if we have to parse the whole document
  9.  
  10.         //or only the part we want ???
  11.  
  12.        
  13.  
  14.         private boolean in_curr_tag = false;
  15.  
  16.         private boolean in_obs_tag = false;
  17.  
  18.        
  19.  
  20.        
  21.  
  22.         private ParsedExampleDataSet peds = new ParsedExampleDataSet();
  23.  
  24.        
  25.  
  26.         public ParsedExampleDataSet getParsedData(){
  27.  
  28.                 return this.peds;
  29.  
  30.         }
  31.  
  32.        
  33.  
  34.         @Override
  35.  
  36.         public void startDocument() throws SAXException {
  37.  
  38.                 this.peds = new ParsedExampleDataSet();
  39.  
  40.         }
  41.  
  42.        
  43.  
  44.         @Override
  45.  
  46.         public void endDocument() throws SAXException {
  47.  
  48.                 //nothing to do here
  49.  
  50.         }
  51.  
  52.        
  53.  
  54.         /*
  55.  
  56.          * Gets be called on opening tags like
  57.  
  58.          * <tag>
  59.  
  60.          * Can provide attribute(s), when xml was like:
  61.  
  62.          * <tag attribute="attributeValue">*/
  63.  
  64.          @Override
  65.  
  66.          public void startElement(String namespaceURI, String localName,
  67.  
  68.                                                                 String qName, Attributes atts)throws SAXException{
  69.  
  70.                  
  71.  
  72.                  if(localName.equals("frbny:CURR")){
  73.  
  74.                          this.in_curr_tag = true;
  75.  
  76.                  }else if(localName.equals("frbny:OBS_VALUE")){
  77.  
  78.                          this.in_obs_tag = true;
  79.  
  80.                  }
  81.  
  82.                  
  83.  
  84.                  
  85.  
  86.                
  87.  
  88.          }
  89.  
  90.          
  91.  
  92.          //Called on closing tags like </tag>
  93.  
  94.          @Override
  95.  
  96.          public void endElement(String namespaceURI, String localName, String qName) throws SAXException{
  97.  
  98.                  
  99.  
  100.                  
  101.  
  102.                  if(localName.equals("frbny:CURR")){
  103.  
  104.                          this.in_curr_tag = false;
  105.  
  106.                  }else if(localName.equals("frbny:OBS_VALUE")){
  107.  
  108.                          this.in_obs_tag = false;
  109.  
  110.                  }
  111.  
  112.                  
  113.  
  114.                
  115.  
  116.          }
  117.  
  118.          
  119.  
  120.          /** Gets be called on the following structure:
  121.  
  122.       * <tag>characters</tag> */
  123.  
  124.      @Override
  125.  
  126.     public void characters(char ch[], int start, int length) {
  127.  
  128.          
  129.  
  130.          if(this.in_curr_tag){
  131.  
  132.                  peds.setExtractedString(new String(ch, start, length));
  133.  
  134.          }
  135.  
  136.    
  137.  
  138.     }
  139.  
  140.  
  141.  
  142. }
Parsed in 0.042 seconds, using GeSHi 1.0.8.4

When i run this I get the string but it's the last entry in the XML file instead of the first one which is above and I want to be able to go through each entry in the XML file and just extract the OBS_VALUE and the CURR entry but I want to start from the top and go down not start at the bottom and work my way up.
My ParsingXML.java is the same as yours PlusMinus no modifications, the parsedexampledataset.java is the same except i added methods to handle doubles for the OBS_VALUE in the above XML. Any help is appreciated

Thanks in advance
Anthony
Ant1
Freshman
Freshman
 
Posts: 4
Joined: Sun Feb 17, 2008 11:56 pm

Postby plusminus » Mon Feb 18, 2008 1:39 am

Hello Anthony,

I would do it that way:
Additionally create a (Array)List of ResultSets. And every time the parser reaches this tag :darrow: , add a new ParsedExampleDataSet to the List:
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. </frbny:Obs>
Parsed in 0.000 seconds, using GeSHi 1.0.8.4


Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby rajuk » Tue Feb 26, 2008 4:13 am

Hello,

I am trying to access the xml file which in my local tomcat(localhost). but i am getting this exception

java.net.ConectException:localhost/127.0.0.1:8080 - Connection refused exception.

My code is :

URL url = new URL("http://localhost:8080/abc/service.xml");

Document doc = db.parse(new InputSource(url.openStream()));


Can you help me to resolve this issue.

Thanks in advance,

rajuk
rajuk
Freshman
Freshman
 
Posts: 8
Joined: Tue Feb 26, 2008 3:52 am

Postby rajuk » Tue Feb 26, 2008 4:27 am

I forget to mention that I tried with

URL url = new URL("http://127.0.0.1:8080/ebp/service.xml");

-rajuk
rajuk
Freshman
Freshman
 
Posts: 8
Joined: Tue Feb 26, 2008 3:52 am

Prasing XML data returned as response from web service

Postby gvkreddyvamsi » Wed Feb 27, 2008 6:37 am

HI,

Thank you very much..

I understood how to parse data stored as a file on web server . But how to parse XML data returned from web service dynamically..

Here is my application...attached full suource..

How i can parse value stored on double node on XML repsonse..

by

vamsi
Attachments
CurrencyConvertWS.zip
Full source to access currency converter web service
(37.53 KiB) Downloaded 1714 times
gvkreddyvamsi
Developer
Developer
 
Posts: 43
Joined: Mon Jan 21, 2008 5:10 am
Location: INDIA

parsing the content of the tags not the attributes

Postby Ant1 » Thu Feb 28, 2008 1:04 am

Hello again

my question this time is I want to parse the contents of the tag not the attributes like in the example here the tagwithnumber, the attribute is parsed using the methods of the parsedexampledataset class. Well thats what I want to do except with the contents of the tag itself here is my code

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.  /** Gets be called on the following structure:
  3.  
  4.       * <tag>characters</tag> */
  5.  
  6.      @Override
  7.  
  8.     public void characters(char ch[], int start, int length) {
  9.  
  10.          
  11.  
  12.          if(this.in_curr_tag){
  13.  
  14.                  peds.setExtractedString(new String(ch, start, length));
  15.  
  16.          }
  17.  
  18.          if(this.in_obs_tag){
  19.  
  20.                  String s = peds.getExtractedString();
  21.  
  22.                  Double d = Double.parseDouble(s);
  23.  
  24.                  peds.setExtractedDouble(d);
  25.  
  26.                
  27.  
  28.          }
  29.  
  30.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Here is the tag I want to parse


Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <frbny:OBS_VALUE>0.9417</frbny:OBS_VALUE>
  3.  
  4.  
Parsed in 0.000 seconds, using GeSHi 1.0.8.4


I know I'm not using the setExtractedString method for the Double but thats what I don't understand how would I use this method to print out the value of the tag since its a Double I'm thinking I could just create a new method thats exactly the same except it handles Doubles instead of characters but I'm not sure thats a good idea any advice on how to do this is appreciated

Thanks in advance
Anthony
Ant1
Freshman
Freshman
 
Posts: 4
Joined: Sun Feb 17, 2008 11:56 pm

Postby plusminus » Thu Feb 28, 2008 2:10 am

Hello anthony,

with the code you posted I cannot see the purpose of "this.in_curr_tag" :?:

I would just do it like that:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.       if(this.in_obs_tag){
  2.            peds.setExtractedDouble(Double.parseDouble(new String(ch, start, length)));
  3.       }
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

getting null when using ArrayList for tags

Postby Ant1 » Sat Mar 08, 2008 5:19 am

Hello again PlusMinus first let me say thanks for all the help with my two questions and the advice given has helped but now I'm stuck again :cry:

I've used the ArrayList to store the 22 tags I need and I try to access them in the characters method but when I run the emulator all I get is a message saying null and I don't even get the double values here is my code again

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. import java.util.ArrayList;
  3.  
  4. import org.xml.sax.Attributes;
  5. import org.xml.sax.SAXException;
  6. import org.xml.sax.helpers.DefaultHandler;
  7.  
  8. public class ExampleHandler extends DefaultHandler {
  9.        
  10.        
  11.         //test tags see if we have to parse the whole document
  12.         //or only the part we want ???
  13.        
  14.         private boolean in_curr_tag = false;
  15.         private boolean in_obs_tag = false;
  16.        
  17.         //ArrayList to hold all the time we hit the closing tags </in_curr_tag>
  18.         private ArrayList<ParsedExampleDataSet> list = new ArrayList<ParsedExampleDataSet>(22);
  19.        
  20.         private ParsedExampleDataSet peds = new ParsedExampleDataSet();
  21.        
  22.         public ParsedExampleDataSet getParsedData(){
  23.                 return this.peds;
  24.         }
  25.        
  26.         @Override
  27.         public void startDocument() throws SAXException {
  28.                 this.peds = new ParsedExampleDataSet();
  29.         }
  30.        
  31.         @Override
  32.         public void endDocument() throws SAXException {
  33.                 //nothing to do here
  34.         }
  35.        
  36.         /*
  37.          * Gets be called on opening tags like
  38.          * <tag>
  39.          * Can provide attribute(s), when xml was like:
  40.          * <tag attribute="attributeValue">*/
  41.          @Override
  42.          public void startElement(String namespaceURI, String localName,
  43.                                                                 String qName, Attributes atts)throws SAXException{
  44.                  
  45.                  if(localName.equals("frbny:CURR")){
  46.                          this.in_curr_tag = true;
  47.                  }else if(localName.equals("frbny:OBS_VALUE")){
  48.                          this.in_obs_tag = true;
  49.                  }
  50.          }
  51.          
  52.          //Called on closing tags like </tag>
  53.          @Override
  54.          public void endElement(String namespaceURI, String localName, String qName) throws SAXException{
  55.                  
  56.                  
  57.                  if(localName.equals("frbny:CURR")){
  58.                         //add all 22 tags to the ArrayList
  59.                          for(int i = 1; i < list.size(); i++){
  60.                                  list.add(i, peds);
  61.                          }
  62.                          //testing purposes only
  63.                          //peds.setExtractedInt(list.size());
  64.                          this.in_curr_tag = false;
  65.                  }else if(localName.equals("frbny:OBS_VALUE")){
  66.                          this.in_obs_tag = false;
  67.                  }
  68.                  
  69.                
  70.          }
  71.          
  72.          /** Gets be called on the following structure:
  73.       * <tag>characters</tag> */
  74.      @Override
  75.     public void characters(char ch[], int start, int length) {
  76.          
  77.          if(this.in_curr_tag){ 
  78.                  peds = list.get(0);
  79.                  peds.setExtractedString(new String(ch, start, length));
  80.          }
  81.          if(this.in_obs_tag){
  82.                  peds.setExtractedDouble(Double.parseDouble(new String(ch, start, length)));
  83.          }
  84.          
  85.          
  86.     }
  87. }
  88.  
  89.  
Parsed in 0.045 seconds, using GeSHi 1.0.8.4


I'm not sure if I need another for loop to access the ParsedExampleDataSets or not but I don't think so. My question is why am I not able to access the individual tags of the file, I have overloaded the setExtractedString method in the ParsedExampleDataSet class to accept an int along with the String so I can run through the list but again I am not sure if this is necessary. I have gone through google's webpage for the ArrayList class I don't think I missed anything but many eyes are better then one :wink: Thanks for any help in advance again

Anthony
Ant1
Freshman
Freshman
 
Posts: 4
Joined: Sun Feb 17, 2008 11:56 pm

Top
Next

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 9 guests