andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

Parsing XML from the Net - Using the SAXParser

Goto page 1, 2, 3 ... 13, 14, 15  Next
 
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials
Author Message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Sat Dec 22, 2007 6:12 pm    Post subject: Parsing XML from the Net - Using the SAXParser Reply with quote

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.

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

Difficulty: 1 of 5 Smile

What it will look like:


Description:
0.) In this tutorial we are going to parse the following XML-File located at the following url: http://www.anddev.org/images/tut/basic/parsingxml/example.xml :
XML:
<?xml version="1.0"?>
<outertag>
     <innertag sampleattribute="innertagAttribute">
          <mytag>
               anddev.org rulez =)
          </mytag>
          <tagwithnumber thenumber="1337"/>
     </innertag>
</outertag>


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 Smile

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.
Java:
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle icicle) {
          super.onCreate(icicle);

          /* Create a new TextView to display the parsingresult later. */
          TextView tv = new TextView(this);
          try {
               /* Create a URL we want to load some xml-data from. */
               URL url = new URL("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");

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

               /* Get the XMLReader of the SAXParser we created. */
               XMLReader xr = sp.getXMLReader();
               /* Create a new ContentHandler and apply it to the XML-Reader*/
               ExampleHandler myExampleHandler = new ExampleHandler();
               xr.setContentHandler(myExampleHandler);
               
               /* Parse the xml-data from our URL. */
               xr.parse(new InputSource(url.openStream()));
               /* Parsing has finished. */

               /* Our ExampleHandler now provides the parsed data to us. */
               ParsedExampleDataSet parsedExampleDataSet =
                                             myExampleHandler.getParsedData();

               /* Set the result to be displayed in our GUI. */
               tv.setText(parsedExampleDataSet.toString());
               
          } catch (Exception e) {
               /* Display any Error to the GUI. */
               tv.setText("Error: " + e.getMessage());
               Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
          }
          /* Display the TextView. */
          this.setContentView(tv);
     }


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:
XML:
<outertag>

the Handler-Function:
Java:
     @Override
     public void startElement(String namespaceURI, String localName,
               String qName, Attributes atts) throws SAXException {
     }

gets called. Where in this case localName will be "outertag".
The same happens on closing tags, like:
XML:
</outertag>

Here the equivalent 'closing'-method that gets called:
Java:
     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
     }

In XML you can put any characters you want between a opening and an closing tag, like this:
XML:
          <mytag>
               anddev.org rulez =)
          </mytag>

When the Parser reaches such a Tag, the following method gets called, providing the characters between the opening and the closing tag:
Java:
     /** Gets be called on the following structure:
      * <tag>characters</tag> */

     @Override
    public void characters(char ch[], int start, int length) {
          String textBetween = new String(ch, start, length);
    }


Finally on the start/end of each document the following functions get called:
Java:
     @Override
     public void startDocument() throws SAXException {
          // Do some startup if needed
     }

     @Override
     public void endDocument() throws SAXException {
          // Do some finishing work if needed
     }


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:

Java:
     // ===========================================================
     // Fields
     // ===========================================================
     
     private boolean in_outertag = false;
     private boolean in_innertag = false;
     private boolean in_mytag = false;


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.
Java:
     @Override
     public void startElement(String namespaceURI, String localName,
               String qName, Attributes atts) throws SAXException {
          if (localName.equals("outertag")) {
               this.in_outertag = true;
          }else if (localName.equals("innertag")) {
               this.in_innertag = true;
          }else if (localName.equals("mytag")) {
               this.in_mytag = true;
          }else if (localName.equals("tagwithnumber")) {
               String attrValue = atts.getValue("thenumber");
               int i = Integer.parseInt(attrValue);
               myParsedExampleDataSet.setExtractedInt(i);
          }
     }


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

Java:
     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
          if (localName.equals("outertag")) {
               this.in_outertag = false;
          }else if (localName.equals("innertag")) {
               this.in_innertag = false;
          }else if (localName.equals("mytag")) {
               this.in_mytag = false;
          }else if (localName.equals("tagwithnumber")) {
               // Nothing to do here
          }
     }


So for example when the Parser reaches the following part:

XML:
          <mytag>
               anddev.org rulez =)
          </mytag>

Our "in_xyz"-booleans indicate in which tag these characters have been 'detected' and easily extract them:
Java:
     /** Gets be called on the following structure:
      * <tag>characters</tag> */

     @Override
    public void characters(char ch[], int start, int length) {
          if(this.in_mytag){
          myParsedExampleDataSet.setExtractedString(new String(ch, start, length));
     }
    }


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:
Java:
     public ParsedExampleDataSet getParsedData() {
          return this.myParsedExampleDataSet;
     }


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


The Full Source:

"/src/your_package_structure/ParsingXML.java"
Java:
package org.anddev.android.parsingxml;

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 ParsingXML extends Activity {
     
     private final String MY_DEBUG_TAG = "WeatherForcaster";

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

          /* Create a new TextView to display the parsingresult later. */
          TextView tv = new TextView(this);
          try {
               /* Create a URL we want to load some xml-data from. */
               URL url = new URL("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");

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

               /* Get the XMLReader of the SAXParser we created. */
               XMLReader xr = sp.getXMLReader();
               /* Create a new ContentHandler and apply it to the XML-Reader*/
               ExampleHandler myExampleHandler = new ExampleHandler();
               xr.setContentHandler(myExampleHandler);
               
               /* Parse the xml-data from our URL. */
               xr.parse(new InputSource(url.openStream()));
               /* Parsing has finished. */

               /* Our ExampleHandler now provides the parsed data to us. */
               ParsedExampleDataSet parsedExampleDataSet =
                                             myExampleHandler.getParsedData();

               /* Set the result to be displayed in our GUI. */
               tv.setText(parsedExampleDataSet.toString());
               
          } catch (Exception e) {
               /* Display any Error to the GUI. */
               tv.setText("Error: " + e.getMessage());
               Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
          }
          /* Display the TextView. */
          this.setContentView(tv);
     }
}


"/src/your_package_structure/ExampleHandler.java"
Java:
package org.anddev.android.parsingxml;

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


public class ExampleHandler extends DefaultHandler{

     // ===========================================================
     // Fields
     // ===========================================================
     
     private boolean in_outertag = false;
     private boolean in_innertag = false;
     private boolean in_mytag = false;
     
     private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();

     // ===========================================================
     // Getter & Setter
     // ===========================================================

     public ParsedExampleDataSet getParsedData() {
          return this.myParsedExampleDataSet;
     }

     // ===========================================================
     // Methods
     // ===========================================================
     @Override
     public void startDocument() throws SAXException {
          this.myParsedExampleDataSet = new ParsedExampleDataSet();
     }

     @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">*/

     @Override
     public void startElement(String namespaceURI, String localName,
               String qName, Attributes atts) throws SAXException {
          if (localName.equals("outertag")) {
               this.in_outertag = true;
          }else if (localName.equals("innertag")) {
               this.in_innertag = true;
          }else if (localName.equals("mytag")) {
               this.in_mytag = true;
          }else if (localName.equals("tagwithnumber")) {
               // Extract an Attribute
               String attrValue = atts.getValue("thenumber");
               int i = Integer.parseInt(attrValue);
               myParsedExampleDataSet.setExtractedInt(i);
          }
     }
     
     /** Gets be called on closing tags like:
      * </tag> */

     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
          if (localName.equals("outertag")) {
               this.in_outertag = false;
          }else if (localName.equals("innertag")) {
               this.in_innertag = false;
          }else if (localName.equals("mytag")) {
               this.in_mytag = false;
          }else if (localName.equals("tagwithnumber")) {
               // Nothing to do here
          }
     }
     
     /** Gets be called on the following structure:
      * <tag>characters</tag> */

     @Override
    public void characters(char ch[], int start, int length) {
          if(this.in_mytag){
          myParsedExampleDataSet.setExtractedString(new String(ch, start, length));
     }
    }
}


"/src/your_package_structure/ParsedExampleDataSet.java"
Java:
package org.anddev.android.parsingxml;

public class ParsedExampleDataSet {
     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;
     }
}


Thats it Smile


Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials


Last edited by plusminus on Sun Jan 06, 2008 6:34 pm; edited 1 time in total
Back to top
View user's profile Send private message Send e-mail Visit poster's website
Katharnavas
Senior Developer
Senior Developer


Joined: 04 Dec 2007
Posts: 100
Location: India

PostPosted: Mon Dec 24, 2007 11:29 am    Post subject: Reply with quote

Hi,
Nice one got the output as stated above.. Looking for more ! Very Happy
Back to top
View user's profile Send private message Visit poster's website Yahoo Messenger
csagar
Junior Developer
Junior Developer


Joined: 06 Jan 2008
Posts: 15

PostPosted: Sun Jan 06, 2008 4:23 pm    Post subject: u r an amazing teacher !! Reply with quote

You are a best teacher plusminus!! The way you explain the things is so simple !! thanx dude for the tutorial Smile
Back to top
View user's profile Send private message
androidbeginner
Junior Developer
Junior Developer


Joined: 05 Feb 2008
Posts: 17

PostPosted: Wed Feb 06, 2008 7:13 am    Post subject: Re: Parsing XML from the Net - Using the SAXParser Reply with quote

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:

XML:
<?xml version="1.0" encoding="ISO-8859-1" ?>
- <!--  Edited with XML Spy v4.2
  -->

- <Phonebook>
- <PhonebookEntry>
  <firstname>John</firstname>
  <lastname>Connor</lastname>
  <Address>5,Downing Street</Address>
  <Phone loc="home">9875674567</Phone>
  <Phone loc="work">9875674567</Phone>
  <Phone loc="mobile">78654562341</Phone>
  </PhonebookEntry>
- <PhonebookEntry>
  <firstname>Peter</firstname>
  <lastname>Roche</lastname>
  <Address>6,Downing Street</Address>
  <Phone loc="home">7814567890</Phone>
  <Phone loc="work">76890556783</Phone>
  <Phone loc="mobile">4562227890</Phone>
  </PhonebookEntry>
  </Phonebook>


Here is the code:
parsingxml.java:

Java:
package org.anddev.android.parsingxml;

import java.net.Proxy;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLConnection;

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 ParsingXML extends Activity {
   
   
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         System.setProperty("http.proxyHost"," 129.188.69.100 ");
         System.setProperty("http.proxyPort","1080");
         System.setProperty("http.nonProxyHosts","10.228.97.76");

         /* Create a new TextView to display the parsingresult later. */
         TextView tv = new TextView(this);
         try {
              /* Create a URL we want to load some xml-data from. */
              URL url = new URL("http://10.232.169.99:8080/phone.xml");
                          URLConnection ucon = url.openConnection();
              /* Get a SAXParser from the SAXPArserFactory. */
              SAXParserFactory spf = SAXParserFactory.newInstance();
              SAXParser sp = spf.newSAXParser();

              /* Get the XMLReader of the SAXParser we created. */
              XMLReader xr = sp.getXMLReader();
              /* Create a new ContentHandler and apply it to the XML-Reader*/
              ExampleHandler myExampleHandler = new ExampleHandler();
              xr.setContentHandler(myExampleHandler);
             
              /* Parse the xml-data from our URL. */
              xr.parse(new InputSource(url.openStream()));
              /* Parsing has finished. */

              /* Our ExampleHandler now provides the parsed data to us. */
              ParsedExampleDataSet parsedExampleDataSet =
                                            myExampleHandler.getParsedData();

              /* Set the result to be displayed in our GUI. */
              tv.setText(parsedExampleDataSet.toString());
             
         } catch (Exception e) {
              /* Display any Error to the GUI. */
              tv.setText("Error: " + e.getMessage());
             
         }
         /* Display the TextView. */
         this.setContentView(tv);
    }
}


ParsedExampleDataSet.java

Java:
package org.anddev.android.parsingxml;

public class ParsedExampleDataSet {
    private String firstname = null;
    private String lastname=null;
    private String Address=null;
    private String Phone=null;
    private String homephone=null;
    private String workphone=null;
    private String mobilephone=null;

    public String getfirstname() {
         return firstname;
    }
    public void setfirstname(String firstname) {
         this.firstname = firstname;
    }
    public String getlastname(){
     return lastname;
     
    }
    public void setlastname(String lastname){
     this.lastname=lastname;
    }
    public String getAddress(){
     return Address;
    }
public void setAddress(String Address){
     this.Address=Address;
}
    public String getPhone(){
     return Phone;
    }
    public void sethomePhone(String homePhone){
     this.homephone=homePhone;
    }
    public void setworkPhone(String homePhone){
     this.homephone=homePhone;
    }
    public void setmobilePhone(String homePhone){
     this.homephone=homePhone;
    }
     
   
    public String toString(){
         return "firstname = " + this.firstname + "\n" + "lastname=" + this.lastname + "\n" + "Address=" + this.Address+ "\n"  + "homephone=" + this.homephone + "\n" + "workphone=" + this.workphone + "\n" + "mobilephone=" + this.mobilephone;
                   
    }
}


ExampleHandler.java:

Java:
package org.anddev.android.parsingxml;

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


public class ExampleHandler extends DefaultHandler{

     // ===========================================================
     // Fields
     // ===========================================================
     
     private boolean in_outertag = false;
     private boolean in_innertag = false;
     private boolean in_firstname = false;
     private boolean in_lastname= false;
     private boolean in_Address=false;
     private boolean in_Phone=false;
     private boolean in_homePhone=false;
     private boolean in_workPhone=false;
     private boolean in_mobilePhone=false;
     
     
     private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();

     // ===========================================================
     // Getter & Setter
     // ===========================================================

     public ParsedExampleDataSet getParsedData() {
          return this.myParsedExampleDataSet;
     }

     // ===========================================================
     // Methods
     // ===========================================================
     @Override
     public void startDocument() throws SAXException {
          this.myParsedExampleDataSet = new ParsedExampleDataSet();
     }

     @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">*/

     @Override
     public void startElement(String namespaceURI, String localName,
               String qName, Attributes atts) throws SAXException {
          if (localName.equals("PhoneBook")) {
               this.in_outertag = true;
          }else if (localName.equals("PhonebookEntry")) {
               this.in_innertag = true;
          }else if (localName.equals("firstname")) {
               this.in_firstname = true;
          }else if (localName.equals("lastname"))  {
            this.in_lastname= true;
          }else if(localName.equals("Address"))  {
            this.in_Address= true;
          }else if (localName.equals("Phone")){
           String phoneattr=atts.getValue("loc");
               if(phoneattr.equals("home")){
               this.in_homePhone=true;}
          }else if (localName.equals("Phone")){
            String phoneattr=atts.getValue("loc");
               if(phoneattr.equals("work")){
                this.in_workPhone=true;}
         }else if (localName.equals("Phone")){
           String phoneattr=atts.getValue("loc");
                if(phoneattr.equals("mobile")){
                 this.in_mobilePhone=true;
              }
                      }   
          }
           
            //else if (localName.equals("tagwithnumber")) {
         // }
               // Extract an Attribute
              // String attrValue = atts.getValue("thenumber");
              // int i = Integer.parseInt(attrValue);
              // myParsedExampleDataSet.setExtractedInt(i);
        //  }
     
     
     /** Gets be called on closing tags like:
      * </tag> */

     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
          if (localName.equals("Phonebook")) {
               this.in_outertag = false;
          }else if (localName.equals("PhonebookEntry")) {
               this.in_innertag = false;
          }else if (localName.equals("firstname")) {
               this.in_firstname = false;
          }else if (localName.equals("lastname"))  {
            this.in_lastname= false;
          }else if(localName.equals("Address"))  {
            this.in_Address= false;
          }else if(localName.equals("Phone"))   {
            this.in_Phone=false;
          }
     }
     
     /** Gets be called on the following structure:
      * <tag>characters</tag> */

     @Override
    public void characters(char ch[], int start, int length) {
          if(this.in_firstname){
          myParsedExampleDataSet.setfirstname(new String(ch, start, length));
          }
          if(this.in_lastname){
          myParsedExampleDataSet.setlastname(new String(ch, start, length));
          }
          if(this.in_Address){
            myParsedExampleDataSet.setAddress(new String(ch, start, length));
          }
          if(this.in_homePhone){
            myParsedExampleDataSet.sethomePhone(new String(ch, start, length));
          }
          if(this.in_workPhone){
            myParsedExampleDataSet.setworkPhone(new String(ch, start, length));
          }
          if(this.in_mobilePhone){
            myParsedExampleDataSet.setmobilePhone(new String(ch, start, length));
          }
    }
}
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Wed Feb 06, 2008 5:05 pm    Post subject: Reply with quote

Hello androidbeginner,

in startelement you have the following:
Java:
         }else if (localName.equals("Phone")){
           String phoneattr=atts.getValue("loc");
               if(phoneattr.equals("home")){
               this.in_homePhone=true;}
          }else if (localName.equals("Phone")){
            String phoneattr=atts.getValue("loc");
               if(phoneattr.equals("work")){
                this.in_workPhone=true;}
         }else if (localName.equals("Phone")){
           String phoneattr=atts.getValue("loc");
                if(phoneattr.equals("mobile")){
                 this.in_mobilePhone=true;
              }
         }  

This won't work, because if one if-case is true, the rest is checked no more Exclamation
Arrow here the two lower ones never get checked.
So change it to:
Java:
         }else if (localName.equals("Phone")){
           String phoneattr=atts.getValue("loc");
               if(phoneattr.equals("home")){
                 this.in_homePhone=true;
               }else if(phoneattr.equals("work")){
                 this.in_workPhone=true;
               }else if(phoneattr.equals("mobile")){
                 this.in_mobilePhone=true;
              }
         }  


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

Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
gvkreddyvamsi
Developer
Developer


Joined: 21 Jan 2008
Posts: 43
Location: INDIA

PostPosted: Thu Feb 14, 2008 12:32 pm    Post subject: Vamsi Reply with quote

Hi ,


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

by
vamsi
Back to top
View user's profile Send private message Send e-mail Visit poster's website
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Thu Feb 14, 2008 12:48 pm    Post subject: Re: Vamsi Reply with quote

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

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
Ant1
Freshman
Freshman


Joined: 17 Feb 2008
Posts: 4

PostPosted: Mon Feb 18, 2008 12:29 am    Post subject: Reply with quote

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:

XML:
<frbny:Key>
<frbny:FREQ>D</frbny:FREQ>
<frbny:CURR>AUD</frbny:CURR>
<frbny:FX_TIME>12</frbny:FX_TIME>
<frbny:FX_TYPE>S</frbny:FX_TYPE>
</frbny:Key>
&#8722;
     <frbny:Obs OBS_STATUS="A" OBS_CONF="F">
<frbny:TIME_PERIOD>2008-02-15</frbny:TIME_PERIOD>
<frbny:OBS_VALUE>0.9069</frbny:OBS_VALUE>
</frbny:Obs>


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:

Java:

public class ExampleHandler extends DefaultHandler {
     
     
     //test tags see if we have to parse the whole document
     //or only the part we want ???
     
     private boolean in_curr_tag = false;
     private boolean in_obs_tag = false;
     
     
     private ParsedExampleDataSet peds = new ParsedExampleDataSet();
     
     public ParsedExampleDataSet getParsedData(){
          return this.peds;
     }
     
     @Override
     public void startDocument() throws SAXException {
          this.peds = new ParsedExampleDataSet();
     }
     
     @Override
     public void endDocument() throws SAXException {
          //nothing to do here
     }
     
     /*
      * Gets be called on opening tags like
      * <tag>
      * Can provide attribute(s), when xml was like:
      * <tag attribute="attributeValue">*/

      @Override
      public void startElement(String namespaceURI, String localName,
                                        String qName, Attributes atts)throws SAXException{
          
           if(localName.equals("frbny:CURR")){
                this.in_curr_tag = true;
           }else if(localName.equals("frbny:OBS_VALUE")){
                this.in_obs_tag = true;
           }
          
          
          
      }
     
      //Called on closing tags like </tag>
      @Override
      public void endElement(String namespaceURI, String localName, String qName) throws SAXException{
          
          
           if(localName.equals("frbny:CURR")){
                this.in_curr_tag = false;
           }else if(localName.equals("frbny:OBS_VALUE")){
                this.in_obs_tag = false;
           }
          
          
      }
     
      /** Gets be called on the following structure:
      * <tag>characters</tag> */

     @Override
    public void characters(char ch[], int start, int length) {
     
      if(this.in_curr_tag){
           peds.setExtractedString(new String(ch, start, length));
      }
   
    }

}

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
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Mon Feb 18, 2008 1:39 am    Post subject: Reply with quote

Hello Anthony,

I would do it that way:
Additionally create a (Array)List of ResultSets. And every time the parser reaches this tag Arrow Down , add a new ParsedExampleDataSet to the List:
XML:
</frbny:Obs>


Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
rajuk
Freshman
Freshman


Joined: 26 Feb 2008
Posts: 8

PostPosted: Tue Feb 26, 2008 4:13 am    Post subject: Reply with quote

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
Back to top
View user's profile Send private message
rajuk
Freshman
Freshman


Joined: 26 Feb 2008
Posts: 8

PostPosted: Tue Feb 26, 2008 4:27 am    Post subject: Reply with quote

I forget to mention that I tried with

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

-rajuk
Back to top
View user's profile Send private message
gvkreddyvamsi
Developer
Developer


Joined: 21 Jan 2008
Posts: 43
Location: INDIA

PostPosted: Wed Feb 27, 2008 6:37 am    Post subject: Prasing XML data returned as response from web service Reply with quote

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



CurrencyConvertWS.zip
 Description:
Full source to access currency converter web service

Download
 Filename:  CurrencyConvertWS.zip
 Filesize:  37.53 KB
 Downloaded:  733 Time(s)

Back to top
View user's profile Send private message Send e-mail Visit poster's website
Ant1
Freshman
Freshman


Joined: 17 Feb 2008
Posts: 4

PostPosted: Thu Feb 28, 2008 1:04 am    Post subject: parsing the content of the tags not the attributes Reply with quote

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

Java:

 /** Gets be called on the following structure:
      * <tag>characters</tag> */

     @Override
    public void characters(char ch[], int start, int length) {
     
      if(this.in_curr_tag){
           peds.setExtractedString(new String(ch, start, length));
      }
      if(this.in_obs_tag){
           String s = peds.getExtractedString();
           Double d = Double.parseDouble(s);
           peds.setExtractedDouble(d);
          
      }


Here is the tag I want to parse


XML:

<frbny:OBS_VALUE>0.9417</frbny:OBS_VALUE>


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
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Thu Feb 28, 2008 2:10 am    Post subject: Reply with quote

Hello anthony,

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

I would just do it like that:
Java:
     if(this.in_obs_tag){
           peds.setExtractedDouble(Double.parseDouble(new String(ch, start, length)));
      }


Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
Ant1
Freshman
Freshman


Joined: 17 Feb 2008
Posts: 4

PostPosted: Sat Mar 08, 2008 5:19 am    Post subject: getting null when using ArrayList for tags Reply with quote

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 Crying or Very sad

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

Java:


import java.util.ArrayList;

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

public class ExampleHandler extends DefaultHandler {
     
     
     //test tags see if we have to parse the whole document
     //or only the part we want ???
     
     private boolean in_curr_tag = false;
     private boolean in_obs_tag = false;
     
     //ArrayList to hold all the time we hit the closing tags </in_curr_tag>
     private ArrayList<ParsedExampleDataSet> list = new ArrayList<ParsedExampleDataSet>(22);
     
     private ParsedExampleDataSet peds = new ParsedExampleDataSet();
     
     public ParsedExampleDataSet getParsedData(){
          return this.peds;
     }
     
     @Override
     public void startDocument() throws SAXException {
          this.peds = new ParsedExampleDataSet();
     }
     
     @Override
     public void endDocument() throws SAXException {
          //nothing to do here
     }
     
     /*
      * Gets be called on opening tags like
      * <tag>
      * Can provide attribute(s), when xml was like:
      * <tag attribute="attributeValue">*/

      @Override
      public void startElement(String namespaceURI, String localName,
                                        String qName, Attributes atts)throws SAXException{
          
           if(localName.equals("frbny:CURR")){
                this.in_curr_tag = true;
           }else if(localName.equals("frbny:OBS_VALUE")){
                this.in_obs_tag = true;
           }
      }
     
      //Called on closing tags like </tag>
      @Override
      public void endElement(String namespaceURI, String localName, String qName) throws SAXException{
          
          
           if(localName.equals("frbny:CURR")){
               //add all 22 tags to the ArrayList
                for(int i = 1; i < list.size(); i++){
                     list.add(i, peds);
                }
                //testing purposes only
                //peds.setExtractedInt(list.size());
                this.in_curr_tag = false;
           }else if(localName.equals("frbny:OBS_VALUE")){
                this.in_obs_tag = false;
           }
          
          
      }
     
      /** Gets be called on the following structure:
      * <tag>characters</tag> */

     @Override
    public void characters(char ch[], int start, int length) {
     
      if(this.in_curr_tag){   
           peds = list.get(0);
           peds.setExtractedString(new String(ch, start, length));
      }
      if(this.in_obs_tag){
           peds.setExtractedDouble(Double.parseDouble(new String(ch, start, length)));
      }
     
         
    }
}



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
Back to top
View user's profile Send private message
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials All times are GMT + 1 Hour
Goto page 1, 2, 3 ... 13, 14, 15  Next
Page 1 of 15

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.