Parsing XML from the Net - Using the SAXParser

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

Please help og gettting parsing this xml

Postby parimalraj2000 » Mon Nov 10, 2008 1:43 pm

Hello all,

I have the xml file in the below format:

<?xml version="1.0" ?>
- <rss version="2.0">
- <channel>
<title>The Official Pink Site: News + Blogl</title>
<link>http://www.pinkspage.com/news</link>
<description>News + Blog</description>
- <item>
<pubDate>OCTOBER 22, 2008 5:11:00 AM EDT</pubDate>
<title>Official Australian Tour Dates Coming Soon!</title>
<description>To all the fans Down Under who may have missed the exclusive performance tonight - don't worry! We'll soon be bringing you the OFFICIAL tour dates here on P!nk's Funhouse App! Keep checking back and sign up for EMail updates on-line at Pinkspage.com to be the first to know when dates are officially announced in your area.</description>
</item>
</channel>
</rss>

Now I want to parse this xml file and want to display "title" and "description". Can any one help me, how I need to modify the code, so that I can show these details on my screen.

Please help me.
thank you so much for your help in advance.

Regards,
Parimal.
parimalraj2000
Junior Developer
Junior Developer
 
Posts: 18
Joined: Tue Nov 04, 2008 10:01 am

Top

XML parsing issue

Postby parimalraj2000 » Mon Nov 10, 2008 1:44 pm

Posted: Mon Nov 10, 2008 1:43 pm Post subject: Please help og gettting parsing this xml

--------------------------------------------------------------------------------

Hello all,

I have the xml file in the below format:

<?xml version="1.0" ?>
- <rss version="2.0">
- <channel>
<title>The Official Pink Site: News + Blogl</title>
<link>http://www.pinkspage.com/news</link>
<description>News + Blog</description>
- <item>
<pubDate>OCTOBER 22, 2008 5:11:00 AM EDT</pubDate>
<title>Official Australian Tour Dates Coming Soon!</title>
<description>To all the fans Down Under who may have missed the exclusive performance tonight - don't worry! We'll soon be bringing you the OFFICIAL tour dates here on P!nk's Funhouse App! Keep checking back and sign up for EMail updates on-line at Pinkspage.com to be the first to know when dates are officially announced in your area.</description>
</item>
</channel>
</rss>

Now I want to parse this xml file and want to display "title" and "description". Can any one help me, how I need to modify the code, so that I can show these details on my screen.

Please help me.
thank you so much for your help in advance.

Regards,
Parimal.
parimalraj2000
Junior Developer
Junior Developer
 
Posts: 18
Joined: Tue Nov 04, 2008 10:01 am

Postby AJ Quick » Wed Nov 19, 2008 8:23 pm

Great tutorial.

I have a few questions when using something similar to this.

How do I load the xml rows that I want into an array? How do I set this up to be called, rather than run directly from the onCreate commad?

I literally want a function that I can load a URL into.. and get an array back with the title data and link data.
AJ Quick
Junior Developer
Junior Developer
 
Posts: 16
Joined: Wed Nov 19, 2008 8:16 pm

Postby deef » Sat Nov 22, 2008 6:08 pm

Hey plusminus,

Unfortunately I get an error message by the android emulator saying " Error: unknown error "
Do you know what I did wrong?

Thanks in advance.

Cheers, David
deef
Freshman
Freshman
 
Posts: 3
Joined: Sat Nov 22, 2008 6:04 pm

Postby deef » Sat Nov 22, 2008 6:38 pm

deef wrote:Hey plusminus,

Unfortunately I get an error message by the android emulator saying " Error: unknown error "
Do you know what I did wrong?

Thanks in advance.

Cheers, David


It seems like class ParsingXML throws allready in the beginning an exception.
Can somebody help clearing this out, please?
deef
Freshman
Freshman
 
Posts: 3
Joined: Sat Nov 22, 2008 6:04 pm

Postby deef » Sat Nov 22, 2008 8:48 pm

deef wrote:
deef wrote:Hey plusminus,

Unfortunately I get an error message by the android emulator saying " Error: unknown error "
Do you know what I did wrong?

Thanks in advance.

Cheers, David


It seems like class ParsingXML throws allready in the beginning an exception.
Can somebody help clearing this out, please?


I found the problem myself... I forgot to configure the androidManifest.xml permissions :O
deef
Freshman
Freshman
 
Posts: 3
Joined: Sat Nov 22, 2008 6:04 pm

Top

Postby bonny » Sun Nov 30, 2008 11:12 am

Hi all!This tutorial is perfect, but I found one problem. I have to parse a tag like this
<nick>Chat &amp; Voice</nick>
and the parser divide it in ParsedDataSet in " Chat" and " Voice". It seems that &amp; gives some problem,but I can't modify the xml because I'm working on a web service. What can I do?

Edit: I tried a little hack that concatenates the string, and it works, but if exists a better solution..
bonny
Junior Developer
Junior Developer
 
Posts: 19
Joined: Fri Apr 11, 2008 2:08 pm

Postby rigeltrue » Fri Dec 12, 2008 5:12 am

bstubbs wrote:Artur79, did you ever figure out how to solve the missing string?

I'm getting the same results:


ExtractedString =
ExtractedInt = 1337


Anyone else getting this, found a solution? Thanks


Hi
I meet the same proplem.

Chnage the xml file from
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


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


That works.
rigeltrue
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Dec 12, 2008 4:18 am

Postby Artur79 » Sun Dec 14, 2008 5:14 pm

I've saved xml from example to my disc and tried to load it, but cannot even compile cuz Eclipse shows that something is wrong with xml :shock: tried neither main project folder nor res as a location of a file.
Artur79
Developer
Developer
 
Posts: 26
Joined: Fri Sep 26, 2008 12:53 pm

Postby tdi » Mon Dec 29, 2008 11:38 am

rigeltrue wrote:
bstubbs wrote:Artur79, did you ever figure out how to solve the missing string?

I'm getting the same results:


ExtractedString =
ExtractedInt = 1337


Anyone else getting this, found a solution? Thanks


Hi
I meet the same proplem.

Chnage the xml file from
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


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


That works.


Damn, had the same problem. After changing to inline as you said, it works. It is weird imo, valid xml is valid xml.
---
Dariusz Dwornikowski
My CS site
User avatar
tdi
Freshman
Freshman
 
Posts: 7
Joined: Wed Dec 24, 2008 2:17 pm
Location: Poland

How to put the parsed value in the local database?

Postby discover_dileep » Wed Jan 21, 2009 3:06 pm

Hi
Can anybody tell me that how to store the parsed value from webservice into the local databse?After storing it into the local database I want to display the parsed value from databse on the UI.
discover_dileep
Developer
Developer
 
Posts: 33
Joined: Tue Oct 21, 2008 2:19 pm

Postby androooooid » Tue Jan 27, 2009 11:29 pm

How would I get this to work with httpsConnection ?

I am trying the following code...

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. URL url = new URL("https://testsite.com/webservice.asmx/Add?id=" + id);
  2. HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
  3. httpsConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
  4. httpsConnection.connect();
  5. InputStream inputStream = httpsConnection.getInputStream();
  6. /* Parse the xml-data from our URL. */
  7. xr.parse(new InputSource(inputStream));
  8. /* Parsing has finished. */
Parsed in 0.032 seconds, using GeSHi 1.0.8.4


that throws an exception of
Code: Select all
01-27 15:23:50.297: INFO/fail(978): Not trusted server certificate


so I try and allowallhostname before that and now it just fails (doesn't work because httpsConnection is null :oops:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. URL url = new URL("https://testsite.com/webservice.asmx/Add?id=" + id);
  2. HttpsURLConnection httpsConnection = null;
  3. httpsConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
  4. httpsConnection = (HttpsURLConnection) url.openConnection()
  5. httpsConnection.connect();
  6. InputStream inputStream = httpsConnection.getInputStream();
  7. /* Parse the xml-data from our URL. */
  8. xr.parse(new InputSource(inputStream));
  9. /* Parsing has finished. */
Parsed in 0.034 seconds, using GeSHi 1.0.8.4


Update...
Finally figured it out!
Here is the link that helped me
http://groups.google.com/group/android- ... 3b28ad8bbc


I call
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. allowAllSSL();
Parsed in 0.034 seconds, using GeSHi 1.0.8.4

before I use URL and
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. HttpsURLConnection httpsConnection = (HttpsURLConnection)url.openConnection();
  2. httpsConnection.connect();
  3. InputStream inputStream = httpsConnection.getInputStream();
  4.                                                                    
  5. /* Parse the xml-data from our URL. */
  6. xr.parse(new InputSource(inputStream));
  7. /* Parsing has finished. */
  8.  
Parsed in 0.036 seconds, using GeSHi 1.0.8.4
androooooid
Junior Developer
Junior Developer
 
Posts: 17
Joined: Fri Sep 26, 2008 8:47 pm

Problem in parsing XML

Postby manish » Wed Feb 11, 2009 11:14 am

Hi deaf,

I am also facing the same problem. I am trying to parse an XML file which is stored localy in the sdcard but when I am trying to parse it I am getting java.net.MalformedURLException: Protocol not found error. Following is the code which I am trying

SAXParserFactory spf = SAXParserFactory.newInstance();
try {
//get a new instance of parser
SAXParser sp = spf.newSAXParser();
String s = "<?xml version="1.0" encoding="utf-8"?><resources><string name="hello">Hello World, xmlParsing</string><string name="app_name"></string></resources>"; //parse the file and also register this class for call backs
//sp.parse("./sdcard/employees.xml", this);
DefaultHandler myExampleHandler = new DefaultHandler();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(myExampleHandler);
xr.parse(new InputSource(s));

//sp.parse(s, this);
// sp.parse(context.getResources().getXml(R.xml.employees), this)
}catch(SAXException se) {
se.printStackTrace();
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch (IOException ie) {
ie.printStackTrace();
}

deef wrote:
deef wrote:
deef wrote:Hey plusminus,

Unfortunately I get an error message by the android emulator saying " Error: unknown error "
Do you know what I did wrong?

Thanks in advance.

Cheers, David


It seems like class ParsingXML throws allready in the beginning an exception.
Can somebody help clearing this out, please?


I found the problem myself... I forgot to configure the androidManifest.xml permissions :O
manish
Junior Developer
Junior Developer
 
Posts: 21
Joined: Thu Feb 05, 2009 1:06 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby manish » Thu Feb 12, 2009 11:30 am

Hi,

I tried the example written by you. I am getting exception in the xr.parse(new InputSource(url.openStream())) line. Exception is coming in url.openStream().
Please help me.

plusminus wrote:
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.041 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.037 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.036 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.000 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.037 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.037 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.037 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.039 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.039 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.037 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.037 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.044 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.047 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.039 seconds, using GeSHi 1.0.8.4


Thats it :)


Regards,
plusminus
manish
Junior Developer
Junior Developer
 
Posts: 21
Joined: Thu Feb 05, 2009 1:06 pm

Postby mel » Thu Feb 12, 2009 7:03 pm

hey plusminus, I run your example and get this error of: "Error:unknown error" on the screen, any idea?

Edit...

the thing that is doing the error is this:

new InputSource(url.openStream())


this is on the ParsingXML.java

:S
Attachments
error.JPG
error on xml parser
error.JPG (5.04 KiB) Viewed 6846 times
mel
Junior Developer
Junior Developer
 
Posts: 12
Joined: Thu Feb 12, 2009 6:53 pm

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 6 guests