Parsing XML from the Net - Using the SAXParser

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

Re: Parsing XML from the Net - Using the SAXParser

Postby ancientgeek » Fri Apr 29, 2011 2:16 am

Hi,
thanks for the example, i understand parsing more clearly now. But I was thinking how would you go abt extracting the data having this kind of xml?

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <varfield id="040" i1=" " i2=" ">
  2. <subfield label="a">xxx</subfield>
  3. <subfield label="c">xxx</subfield>
  4. </varfield>
  5. <varfield id="099" i1=" " i2=" ">
  6. <subfield label="a">HIG</subfield>
  7. </varfield>
  8.  
Parsed in 0.002 seconds, using GeSHi 1.0.8.4


Say I only want to extract the values from both subfield labels based on the attribute value of varfield id="040". How do you do this? Because I have multiple similar tags like this that I have to extract data based on attribute values. I think I have to use for loop and iterate through the entire list of "varfield" tags.

Thanks,

Joel
ancientgeek
Freshman
Freshman
 
Posts: 5
Joined: Mon Apr 25, 2011 7:33 am

Top

Re: Parsing XML from the Net - Using the SAXParser

Postby Menor » Tue May 03, 2011 8:57 pm

ancientgeek wrote:Hi,
thanks for the example, i understand parsing more clearly now. But I was thinking how would you go abt extracting the data having this kind of xml?

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <varfield id="040" i1=" " i2=" ">
  2. <subfield label="a">xxx</subfield>
  3. <subfield label="c">xxx</subfield>
  4. </varfield>
  5. <varfield id="099" i1=" " i2=" ">
  6. <subfield label="a">HIG</subfield>
  7. </varfield>
  8.  
Parsed in 0.002 seconds, using GeSHi 1.0.8.4


Say I only want to extract the values from both subfield labels based on the attribute value of varfield id="040". How do you do this? Because I have multiple similar tags like this that I have to extract data based on attribute values. I think I have to use for loop and iterate through the entire list of "varfield" tags.

Thanks,

Joel


Use some flag when you are reading the <varfield id="040" i1=" " i2=" ">...
If the id == 040, set flag storeInformation = true
Before storing the information, you need to check if storeInformation = true, if is true, store the information, else do nothing...
When the element ends, set storeInformation = false again...

I think that it works...

Try it...
Menor
Experienced Developer
Experienced Developer
 
Posts: 83
Joined: Mon Apr 11, 2011 3:45 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby ancientgeek » Wed May 04, 2011 3:05 am

Menor wrote:
ancientgeek wrote:Hi,
thanks for the example, i understand parsing more clearly now. But I was thinking how would you go abt extracting the data having this kind of xml?

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <varfield id="040" i1=" " i2=" ">
  2. <subfield label="a">xxx</subfield>
  3. <subfield label="c">xxx</subfield>
  4. </varfield>
  5. <varfield id="099" i1=" " i2=" ">
  6. <subfield label="a">HIG</subfield>
  7. </varfield>
  8.  
Parsed in 0.002 seconds, using GeSHi 1.0.8.4


Say I only want to extract the values from both subfield labels based on the attribute value of varfield id="040". How do you do this? Because I have multiple similar tags like this that I have to extract data based on attribute values. I think I have to use for loop and iterate through the entire list of "varfield" tags.

Thanks,

Joel


Use some flag when you are reading the <varfield id="040" i1=" " i2=" ">...
If the id == 040, set flag storeInformation = true
Before storing the information, you need to check if storeInformation = true, if is true, store the information, else do nothing...
When the element ends, set storeInformation = false again...

I think that it works...

Try it...


Hey Menor,

Thanks for replying. Haha. But I managed to retrieve the data based on the attribute values alone ^^. Now I'm trying to store the data into a list and the displaying it. Would appreciate it if you could point me in the right direction ^^.
ancientgeek
Freshman
Freshman
 
Posts: 5
Joined: Mon Apr 25, 2011 7:33 am

Re: Parsing XML from the Net - Using the SAXParser

Postby Minorko » Sat May 07, 2011 1:54 pm

Hi, I'm try parse xml from sd.
pPath = "/sdcard/games/CC/resourses/xml/levels/harbor.xml";
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class BaseXMLParser {
  2.  
  3.     public BaseXMLParser(String pPath) {
  4.         try {
  5.             File file = new File(pPath);
  6.  
  7.             SAXParserFactory mFactory = SAXParserFactory.newInstance();
  8.             SAXParser mParser = mFactory.newSAXParser();
  9.  
  10.             XMLReader mReader = mParser.getXMLReader();
  11.  
  12.             LevelHandler myExampleHandler = new LevelHandler();
  13.  
  14.             mReader.setContentHandler(myExampleHandler);
  15.  
  16.             FileInputStream fis = new FileInputStream(file);
  17.             InputStreamReader isr = new InputStreamReader(fis);
  18.             InputSource ip = new InputSource(isr);
  19.  
  20.             mReader.parse(ip);
  21.  
  22.             ArrayList<ParsedObjectDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();
  23.  
  24.         } catch (Exception e) {
  25.             Log.e("parse",e.toString());
  26.         }
  27.  
  28.     }
  29. }
Parsed in 0.034 seconds, using GeSHi 1.0.8.4

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class LevelHandler extends DefaultHandler{
  2.      
  3.     // ===========================================================
  4.     // Fields
  5.     // ===========================================================
  6.     private int mIndex = 0;
  7.     private boolean in_element = false;
  8.     private boolean in_id = false;
  9.     private boolean in_name = false;
  10.     private boolean in_coodrX = false;
  11.     private boolean in_coordY = false;
  12.     private boolean in_cellX = false;
  13.     private boolean in_cellY = false;
  14.  
  15.     private ArrayList<ParsedObjectDataSet> myParsedObjectDataList;
  16.      
  17.     // ===========================================================
  18.     // Getter & Setter
  19.     // ===========================================================
  20.      
  21.     public ArrayList<ParsedObjectDataSet> getParsedData() {
  22.         return this.myParsedObjectDataList;
  23.     }
  24.      
  25.     // ===========================================================
  26.     // Methods
  27.     // ===========================================================
  28.     @Override
  29.     public void startDocument() throws SAXException {
  30.         myParsedObjectDataList = new ArrayList<ParsedObjectDataSet>();
  31.     }
  32.      
  33.     @Override
  34.     public void endDocument() throws SAXException {
  35.         // Nothing to do
  36.     }
  37.      
  38.     /** Gets be called on opening tags like:
  39.      * <tag>
  40.      * Can provide attribute(s), when xml was like:
  41.      * <tag attribute="attributeValue">*/
  42.     @Override
  43.     public void startElement(String namespaceURI, String localName,
  44.                     String qName, Attributes atts) throws SAXException {
  45.         if (localName.equals("ELEMENT")){
  46.             myParsedObjectDataList.add(new ParsedObjectDataSet());
  47.         } else
  48.  
  49.         if (localName.equals("ID")){
  50.             in_id = true;
  51.         } else
  52.  
  53.         if (localName.equals("NAME")){
  54.             in_name = true;
  55.         } else
  56.  
  57.         if (localName.equals("COORD_X")){
  58.             in_coodrX = true;
  59.         } else
  60.  
  61.         if (localName.equals("COORD_Y")){
  62.             in_coordY = true;
  63.         } else
  64.  
  65.         if (localName.equals("CELLS_X")){
  66.             in_cellX = true;
  67.         } else
  68.  
  69.         if (localName.equals("CELLS_Y")){
  70.             in_cellY = true;
  71.         }
  72.     }
  73.            
  74.     /** Gets be called on closing tags like:
  75.      * </tag> */
  76.     @Override
  77.     public void endElement(String namespaceURI, String localName, String qName)
  78.                     throws SAXException {
  79.         if (localName.equals("ELEMENT")){
  80.             myParsedObjectDataList.add(new ParsedObjectDataSet());
  81.             mIndex++;
  82.         } else
  83.  
  84.         if (localName.equals("ID")){
  85.             in_id = false;
  86.         } else
  87.  
  88.         if (localName.equals("NAME")){
  89.             in_name = false;
  90.         } else
  91.  
  92.         if (localName.equals("COORD_X")){
  93.             in_coodrX = false;
  94.         } else
  95.  
  96.         if (localName.equals("COORD_Y")){
  97.             in_coordY = false;
  98.         } else
  99.  
  100.         if (localName.equals("CELLS_X")){
  101.             in_cellX = false;
  102.         } else
  103.  
  104.         if (localName.equals("CELLS_Y")){
  105.             in_cellY = false;
  106.         }
  107.     }
  108.            
  109.     /** Gets be called on the following structure:
  110.      * <tag>characters</tag> */
  111.     @Override
  112.     public void characters(char ch[], int start, int length) {
  113.         String textBetween = new String(ch,start,length);
  114.         if (in_id) {
  115.             myParsedObjectDataList.get(mIndex).setID(Integer.parseInt(textBetween));
  116.         } else
  117.         if (in_name) {
  118.             myParsedObjectDataList.get(mIndex).setName(textBetween);
  119.         } else
  120.         if (in_coodrX) {
  121.             myParsedObjectDataList.get(mIndex).setCoord_X(Integer.parseInt(textBetween));
  122.         } else
  123.         if (in_coordY) {
  124.             myParsedObjectDataList.get(mIndex).setCoord_Y(Integer.parseInt(textBetween));
  125.         } else
  126.         if (in_cellX) {
  127.             myParsedObjectDataList.get(mIndex).setCell_X(Integer.parseInt(textBetween));
  128.         } else
  129.         if (in_cellY) {
  130.             myParsedObjectDataList.get(mIndex).setCell_Y(Integer.parseInt(textBetween));
  131.         }
  132.     }
  133. }
  134.  
Parsed in 0.047 seconds, using GeSHi 1.0.8.4

And I'm getting this error:
Code: Select all
05-07 16:47:02.118: ERROR/parse(29626): org.apache.harmony.xml.ExpatParser$ParseException: At line 10, column 0: junk after document element

Why ?
XML file:
Code: Select all
<?xml version="1.0" encoding="UTF-8"?>
<ELEMENT>
   <ID>309</ID>
   <NAME>port_decoration_container_02.png</NAME>
   <COORD_X>-30</COORD_X>
   <COORD_Y>-85</COORD_Y>
   <CELLS_X>3</CELLS_X>
   <CELLS_Y>2</CELLS_Y>
</ELEMENT>
<ELEMENT>
   <ID>300</ID>
   <NAME>port_building_admin_01.png</NAME>
   <COORD_X>-177</COORD_X>
   <COORD_Y>-409</COORD_Y>
   <CELLS_X>9</CELLS_X>
   <CELLS_Y>9</CELLS_Y>
</ELEMENT>
Minorko
Freshman
Freshman
 
Posts: 6
Joined: Thu May 05, 2011 3:41 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby emha » Wed May 11, 2011 7:49 pm

Hey all,

i have the following code in my ExampleHandler:

Code: Select all
package de.malte.heyenga.ideenfrische;


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 {
   
     // only the relevant tags
     
   private boolean in_outertag = false;
    private boolean in_innertag = false;
    private boolean in_mytag = false;
    private boolean in_jahr = false;
     
     private ArrayList<ParsedExampleDataSet> list = new ArrayList<ParsedExampleDataSet>(22); // 22 == capacity
       
     public ArrayList<ParsedExampleDataSet> getParsedData(){
          return this.list;
     }
     
     @Override
     public void startDocument() throws SAXException {
          //nothing to do here
     }
     
     @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("referenzen")){
                list.add(new ParsedExampleDataSet());
                this.in_outertag = true;
           }else if(localName.equals("referenz")){
                this.in_innertag = true;
           }else if (localName.equals("kunde")) {
               this.in_mytag = true;
           }else if (localName.equals("jahr")) {
                 this.in_jahr = true;
           }
      }
     
      //Called on closing tags like </tag>
      @Override
      public void endElement(String namespaceURI, String localName, String qName) throws SAXException{
         if(localName.equals("referenzen")){
              this.in_outertag = false;
         }else if(localName.equals("referenz")){
              this.in_innertag = false;
         }else if (localName.equals("kunde")) {
             this.in_mytag = false;
         }else if (localName.equals("jahr")) {
               this.in_jahr = false;
         }
      }
     
      /** Gets be called on the following structure:
      * <tag>characters</tag> */
     @Override
    public void characters(char ch[], int start, int length) {
     // getLast()-Function is probably not existing, need to do on your own
      if(this.in_mytag){ 
           list.getLast().setExtractedString(new String(ch, start, length));
      }
      if(this.in_jahr){
            list.getLast().setExtractedDouble(Double.parseDouble(new String(ch, start, length)));
      }
    }
}


Now he says
Code: Select all
The method getLast() is undefined for the type
    ArrayList<ParsedExampleDataSet>


Where i have to declare it? And with what in it? I'am new, so I feel really sorry for the stupid question :(

I'am from Germany so please forgive my bad english.

Best regards,
emha
emha
Freshman
Freshman
 
Posts: 2
Joined: Wed May 11, 2011 7:46 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby emha » Thu May 12, 2011 8:54 pm

No answer?
emha
Freshman
Freshman
 
Posts: 2
Joined: Wed May 11, 2011 7:46 pm

Top

Re: Parsing XML from the Net - Using the SAXParser

Postby jesini » Wed May 18, 2011 11:55 am

Hi Friend could you please help me parse this xml coding, its urgent - <Quiz>
- <Topics id="1" Topicname="Essentials">
- <Question number="1" title="True or False: Compasses always point to true north.">
<Option Number="A" title="True" />
<Option Number="B" title="False" correct="True" description="False, compasses point to magnetic north – the difference varies between where you are in the world." />
</Question>
- <Question number="2" title="If the moon rises before the sun has set, the illuminated side faces this direction:">
<Option Number="A" title="North" />
<Option Number="B" title="South" />
<Option Number="C" title="West" correct="True" description="The illuminated side of the moon always points west." />
<Option Number="D" title="East" />
</Question>


thanks in advance
jesini
Freshman
Freshman
 
Posts: 2
Joined: Tue May 17, 2011 8:12 am

Re: Parsing XML from the Net - Using the SAXParser

Postby misu_cosma@yahoo.com » Wed Jun 08, 2011 6:49 pm

Hey I'm doing an app in wich I use a distant database,and android KSOAP service and what I need is some java/android code to acces the database(retriecve/put data)
misu_cosma@yahoo.com
Freshman
Freshman
 
Posts: 7
Joined: Mon May 09, 2011 11:03 am

Re: Parsing XML from the Net - Using the SAXParser

Postby misu_cosma@yahoo.com » Wed Jun 08, 2011 6:49 pm

Hey I'm doing an app in wich I use a distant database,and android KSOAP service and what I need is some java/android code to acces the database(retriecve/put data)


Plase help!
misu_cosma@yahoo.com
Freshman
Freshman
 
Posts: 7
Joined: Mon May 09, 2011 11:03 am

Re: Parsing XML from the Net - Using the SAXParser

Postby DKode » Mon Jun 13, 2011 12:23 pm

hey plusminus..
saved and ran your exact code along with the same package names, java file names, and URL.. getting

"Error : null" as message in emulator.. I understand this is because the control flow reaches your catch block at the end.. any idea why this error is occuring?
DKode
Freshman
Freshman
 
Posts: 2
Joined: Mon Jun 13, 2011 12:21 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby DKode » Tue Jun 14, 2011 11:21 am

Tried running your code.. Didn't work =(
Any ideas why? A fast response would be immensely helpful..
DKode
Freshman
Freshman
 
Posts: 2
Joined: Mon Jun 13, 2011 12:21 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby songotho » Wed Jun 15, 2011 3:02 pm

DKode wrote:Tried running your code.. Didn't work =(
Any ideas why? A fast response would be immensely helpful..


Try this example of Padde ( Fri Apr 10, 2009) in Page 5 of this topic.
Hope to help you.
Alex
songotho
Experienced Developer
Experienced Developer
 
Posts: 55
Joined: Tue Mar 03, 2009 1:59 am

parsing image from xml - Using the SAXParser

Postby brindha » Thu Jun 16, 2011 1:52 pm

Hello,

I'm working with android project. It has no image display in xml SAX parser. This is my xml code.
receipe.xml
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  3. <plist version="1.0">
  4.     <dict>
  5. <key>itemChildren</key>
  6. <array>
  7.  
  8. <dict>
  9.                
  10.         <title>Roasted Garlic Jam</title>
  11.         <img>image1.png</img>          
  12.                 <desc>
  13. Ingredients:
  14. 4 heads garlic, large roasted
  15. 1 and peeled
  16. 2 teaspoon olive oil
  17. 1 tablespoon fresh lemon juice
  18. 1/2 teaspoon kosher salt
  19. 1 tablespoon Italian parsley, coarsely
  20. 1 chopped
  21. 1 cayenne pepper, pinch
  22. 1 ground pepper, fresh
  23.  
  24. 1. Chop garlic with knife until it forms a paste. 2. Place in a bowl, add
  25. remaining ingredients. Stir to blend. 3. Use for bruschetta, pizza or grilled meats. Yield 2/3 cup.
  26. </desc>
  27. </dict>
  28. </array>
  29. </dict>
  30. </plist>
Parsed in 0.002 seconds, using GeSHi 1.0.8.4


my source code for retrive datas in xml using xmlSAXParser
XmlAnalyzer.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.EaseApps.jamrecipes;
  2.  
  3. import java.io.IOException;
  4. import java.util.List;
  5.  
  6. import javax.xml.parsers.ParserConfigurationException;
  7. import javax.xml.parsers.SAXParser;
  8. import javax.xml.parsers.SAXParserFactory;
  9.  
  10. import org.xml.sax.Attributes;
  11. import org.xml.sax.InputSource;
  12. import org.xml.sax.SAXException;
  13. import org.xml.sax.XMLReader;
  14. import org.xml.sax.helpers.DefaultHandler;
  15.  
  16. import android.content.Context;
  17. import android.util.Log;
  18. import android.widget.ImageView;
  19.  
  20. public class xmlAnalyzer extends DefaultHandler {
  21.  
  22.         // Used to define what elements we are currently in
  23.         private boolean inImg = false;
  24.         private boolean inTitle = false;
  25.         private boolean inDesc = false;
  26.  
  27.         // Feed and Article objects to use for temporary storage
  28.         private List<String> detailsItem = null;
  29.         private List<String> menuItem = null;
  30.         private List<String> ImgItem = null;
  31.         private String currentMenu = "", currentDetail = "", currentImg = "";
  32.        
  33.        
  34.        
  35.         public void startElement(String uri, String name, String qName,
  36.                         Attributes atts) {
  37.                 if (name.trim().equals("title"))
  38.                         inTitle = true;
  39.                 else if (name.trim().equals("img"))
  40.                         inImg = true;
  41.                 else if (name.trim().equals("desc"))
  42.                         inDesc = true;
  43.         }
  44.  
  45.         public void endElement(String uri, String name, String qName)
  46.                         throws SAXException {
  47.                 if (name.trim().equals("title")) {
  48.                         inTitle = false;
  49.                         menuItem.add(currentMenu);
  50.                         currentMenu = null;
  51.                 } else if (name.trim().equals("img")) {
  52.                         inImg = false;
  53.                         ImgItem.add(currentImg);
  54.                         currentImg = null;
  55.                 } else if (name.trim().equals("desc")) {
  56.                         inDesc = false;
  57.                         detailsItem.add(currentDetail);
  58.                         currentDetail = null;
  59.                 }
  60.         }
  61.  
  62.         public void characters(char ch[], int start, int length) {
  63.                 String chars = (new String(ch).substring(start, start + length));
  64.        
  65.                 try {
  66.                         if (inTitle) {
  67.                                 currentMenu = chars;
  68.                         } else if (inImg) {
  69.                                 currentImg = chars;
  70.                         } else if (inDesc) {
  71.                                 currentDetail = currentDetail + chars;
  72.                         }
  73.                 } catch (Exception e) {
  74.                         Log.e("NewsDroid", e.toString());
  75.                         e.printStackTrace();
  76.                 }
  77.         }
  78.  
  79.         public xmlAnalyzer(Context ctx, List<String> detail, List<String> menu,
  80.                         List<String> img) {
  81.                 detailsItem = detail;
  82.                 menuItem = menu;
  83.                 ImgItem = img;
  84.                 try {
  85.                         SAXParserFactory spf = SAXParserFactory.newInstance();
  86.                         SAXParser sp = spf.newSAXParser();
  87.                         XMLReader xr = sp.getXMLReader();
  88.                         xr.setContentHandler(this);
  89.                         xr.parse(new InputSource(ctx.getAssets().open("recipe.xml")));
  90.  
  91.                 } catch (IOException e) {
  92.                         Log.e("Recipe", e.toString());
  93.                         e.printStackTrace();
  94.                 } catch (SAXException e) {
  95.                         Log.e("Recipe", e.toString());
  96.                         e.printStackTrace();
  97.                 } catch (ParserConfigurationException e) {
  98.                         Log.e("Recipe", e.toString());
  99.                         e.printStackTrace();
  100.                 }
  101.         }
  102.  
  103.         @Override
  104.         public void endDocument() throws SAXException {
  105.  
  106.         }
  107.  
  108. }
Parsed in 0.048 seconds, using GeSHi 1.0.8.4


If any error for this code. because image1.png can not displayed. pls help me it's urgent.
Thanks,
Brindha.A
brindha
Once Poster
Once Poster
 
Posts: 1
Joined: Thu Jun 16, 2011 1:35 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby venkatraman7 » Fri Jul 08, 2011 7:29 am

Hi plus minus,
I tried this sample in my AVD and I got the following exception
07-08 11:57:51.082: ERROR/Exception Caught(271): Host is unresolved: www.anddev.org:80

What does it refers ??
The sample URL you provided in the code also not works in android default browser but works in Firefox :?:

Suggets me solution to handle this
venkatraman7
Developer
Developer
 
Posts: 41
Joined: Tue Nov 16, 2010 6:47 am
Location: Puducherry

Re: Parsing XML from the Net - Using the SAXParser

Postby venkatraman7 » Fri Jul 08, 2011 7:40 am

Hi plus minus,
I tried this sample in my AVD and I got the following exception

07-08 11:57:51.082: ERROR/Exception Caught(271): Host is unresolved: www.anddev.org:80

What does it refers ??
The sample URL you provided in the code also not works in android default browser but works in Firefox :?:

Suggets me solution to handle this
venkatraman7
Developer
Developer
 
Posts: 41
Joined: Tue Nov 16, 2010 6:47 am
Location: Puducherry

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: Google [Bot], Yahoo [Bot] and 8 guests