Parsing XML from the Net - Using the SAXParser

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

Postby relsieg » Mon Nov 30, 2009 6:54 pm

beko wrote:Hi droid friends..
(...)what should i do now ? please help..

Hi beko,

try this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. InputSource source = new InputSource( url.openStream() );
  2. source.setEncoding("ISO-8859-1");
  3.  
  4. /* Parse the xml-data from our URL. */
  5. xr.parse( source );
  6.  
Parsed in 0.030 seconds, using GeSHi 1.0.8.4
relsieg
Freshman
Freshman
 
Posts: 9
Joined: Fri Jul 24, 2009 10:06 pm

Top

weird xml problem

Postby relsieg » Mon Nov 30, 2009 7:23 pm

Hello folks,

I have a weird problem when it comes to reading the values between the tags.
My XML:
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <?xml version="1.0" encoding="ISO-8859-1"?>
  3.  
  4. <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  5.  
  6.         <channel>
  7.  
  8.                 <item>
  9.  
  10.                         <title>Title 1</title>
  11.  
  12.                         <link>aaaaaaaaaaaaa</link>
  13.  
  14.                 </item>
  15.  
  16.                 <item>
  17.  
  18.                         <title>Title 2</title>
  19.  
  20.                         <link>bbbbbbbbbbbbbb</link>
  21.  
  22.                 </item>
  23.  
  24.                 <item>
  25.  
  26.                         <title>Title 3</title>
  27.  
  28.                         <link>cccccccccccccc</link>
  29.  
  30.                 </item>
  31.  
  32.         </channel>
  33.  
  34. </rss>
Parsed in 0.003 seconds, using GeSHi 1.0.8.4


I put the value of the title-tags in a stringlist:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.      public void setExtractedString(String extractedString) {
  2.  
  3.          //  the value should not be empty and not in the list
  4.  
  5.          if( !extractedString.matches("") && !this.allStrings.contains(extractedString) ) {
  6.  
  7.                  this.allStrings.add(extractedString);   
  8.  
  9.          }
  10.  
  11.      }
Parsed in 0.032 seconds, using GeSHi 1.0.8.4


But at the end, I get the following result:
[Title 1, Title 2aaaaaaaaa, Title 3bbbbbbbbbbb]]
This is quite weird because (as seen below) I never touch the link-Tag.
I even logged the status of "this.node_link" in the character method and the start/endElement method to confirm that it is not "true" by mistake

As the "main code" is from this tutorial, I'll only post the handler:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public class FeedHandler extends DefaultHandler{
  3.  
  4.  
  5.  
  6.      // ======= //
  7.  
  8.      //  Nodes  //
  9.  
  10.      // ======= //
  11.  
  12.  
  13.  
  14.      private boolean node_channel               = false;
  15.  
  16.      private boolean node_item                  = false;
  17.  
  18.      private boolean node_title                 = false;
  19.  
  20.      private boolean node_link                  = false;
  21.  
  22.  
  23.  
  24.        
  25.  
  26.      private ContentParser myContentParser = new ContentParser();
  27.  
  28.  
  29.  
  30.      // ===========================================================
  31.  
  32.      // Getter & Setter
  33.  
  34.      // ===========================================================
  35.  
  36.  
  37.  
  38.      public ContentParser getParsedData() {
  39.  
  40.           return this.myContentParser;
  41.  
  42.      }
  43.  
  44.  
  45.  
  46.      // ===========================================================
  47.  
  48.      // Methods
  49.  
  50.      // ===========================================================
  51.  
  52.      @Override
  53.  
  54.      public void startDocument() throws SAXException {
  55.  
  56.           this.myContentParser = new ContentParser();
  57.  
  58.      }
  59.  
  60.  
  61.  
  62.      @Override
  63.  
  64.      public void endDocument() throws SAXException {
  65.  
  66.           // Nothing to do
  67.  
  68.      }
  69.  
  70.  
  71.  
  72.      /** Gets be called on opening tags like:
  73.  
  74.       * <tag>
  75.  
  76.       * Can provide attribute(s), when xml was like:
  77.  
  78.       * <tag attribute="attributeValue">*/
  79.  
  80.      @Override
  81.  
  82.      public void startElement(String namespaceURI, String localName,
  83.  
  84.                String qName, Attributes atts) throws SAXException {
  85.  
  86.  
  87.  
  88.          if( localName.equals("channel") ) {
  89.  
  90.                  this.node_channel = true;
  91.  
  92.          } else if( localName.equals("item") ) {
  93.  
  94.                  this.node_item = true;
  95.  
  96.          } else if( localName.equals("title") ) {
  97.  
  98.                  this.node_title = true;
  99.  
  100.          } else if( localName.equals("link") ) {
  101.  
  102.                  this.node_link = true;
  103.  
  104.          }
  105.  
  106.          
  107.  
  108.  
  109.  
  110.      }
  111.  
  112.  
  113.  
  114.      /** Gets be called on closing tags like:
  115.  
  116.       * </tag> */
  117.  
  118.      @Override
  119.  
  120.      public void endElement(String namespaceURI, String localName, String qName)
  121.  
  122.                throws SAXException {
  123.  
  124.          
  125.  
  126.          if( localName.equals("channel") ) {
  127.  
  128.                  this.node_channel = false;
  129.  
  130.          } else if( localName.equals("item") ) {
  131.  
  132.                  this.node_item = false;
  133.  
  134.          } else if( localName.equals("title") ) {
  135.  
  136.                  this.node_title = false;
  137.  
  138.          } else if( localName.equals("link") ) {
  139.  
  140.                  this.node_link = false;
  141.  
  142.          }
  143.  
  144.      }
  145.  
  146.      
  147.  
  148.      /** Gets be called on the following structure:
  149.  
  150.       * <tag>characters</tag> */
  151.  
  152.      @Override
  153.  
  154.     public void characters(char ch[], int start, int length) {
  155.  
  156.           if(this.node_title){
  157.  
  158.                   // Extrahiere den Wert
  159.  
  160.                   String myStr = String.valueOf(ch);
  161.  
  162.               Log.d("CHARACTERVALUE", myStr);
  163.  
  164.              
  165.  
  166.               this.myContentParser.setExtractedString( myStr.trim() );
  167.  
  168.           }
  169.  
  170.  
  171.  
  172.     }
  173.  
  174. }
Parsed in 0.046 seconds, using GeSHi 1.0.8.4


I even logged the values at the time they were extracted but the result ist the same, as stated above.

Any ideas :(?

Thanks alot,
R.
relsieg
Freshman
Freshman
 
Posts: 9
Joined: Fri Jul 24, 2009 10:06 pm

re:

Postby beko » Mon Nov 30, 2009 10:13 pm

relsieg wrote:
beko wrote:Hi droid friends..
(...)what should i do now ? please help..

Hi beko,

try this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. InputSource source = new InputSource( url.openStream() );
  2. source.setEncoding("ISO-8859-1");
  3.  
  4. /* Parse the xml-data from our URL. */
  5. xr.parse( source );
  6.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


hi rels..
when i set encoding to 8859-1 some traditional characters cause problem.like ş-ı-ö-ç-ğ..
if i set native encoding parser yells 'unknown encoding'..

any help would be great..
beko
Freshman
Freshman
 
Posts: 2
Joined: Tue Nov 24, 2009 11:32 pm

Postby rogerdodger » Wed Dec 02, 2009 7:26 pm

Can someone explain to me how i can do what plusminus said here. I think this is the solution to my problem

plusminus wrote:Hello Anthony,

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


Regards,
plusminus


My xml looks like this:
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <category name="category1">
  2. <asset>1.jpg</asset>
  3. <asset>2.jpg</asset>
  4. </category>
  5. <category name="category2">
  6. <asset>3.jpg</asset>
  7. <asset>4.jpg</asset>
  8. </category>
  9.  
Parsed in 0.002 seconds, using GeSHi 1.0.8.4


And I believe i need an array of ParsedExampleDataSets but don't know where/when to create a new one properly.
rogerdodger
Junior Developer
Junior Developer
 
Posts: 21
Joined: Mon Nov 30, 2009 8:38 am

Postby sourlemon » Fri Dec 04, 2009 4:07 am

I'm using the android SAX Parser, but I'm having trouble parsing this one. Here's the XML.

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <CrossRate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xignite.com/services/">
  3.         <Outcome>RegistrationError</Outcome>
  4.         <Message>XigniteCurrencies: Maximum number of unregistered requests exceeded. Consider registering or subscribing to expand usage. Please visit http://www.xignite.com/RegistrationHelp.aspx for more information.</Message>
  5.         <Identity>IP</Identity>
  6.         <Delay>0</Delay>
  7.         <Type>RealTime</Type>
  8.         <From>
  9.                 <Symbol>USD</Symbol>
  10.         </From>
  11.         <To>
  12.                 <Symbol>USD</Symbol>
  13.         </To>
  14.         <Rate>0</Rate>
  15.         <Bid>0</Bid>
  16.         <Ask>0</Ask>
  17. </CrossRate>
Parsed in 0.004 seconds, using GeSHi 1.0.8.4


When I parse this, it gives me the following error:
adnroid.sax.BadXmlException: Root element name does not match. Expected 'CrossRate', Got: 'http://www.xignite.com/services/:CrossRate'.


But even when I changed it to what was said, it'll still give me the same error (except the part of CrossRate). So I tried this without anything in crossrate. So the head would be <CrossRate>. That works. Does anyone have a workaround for this?

This is my parsing code:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. @Override
  2.         public CurrencyRate parseRate() {
  3.                 Log.i("_________________________________", "parsing messages");
  4.                 final CurrencyRate currentCurrency = new CurrencyRate();
  5.                 RootElement root = new RootElement(CROSSRATE);
  6.  
  7.                 root.getChild(OUTCOME).setEndTextElementListener(new EndTextElementListener(){
  8.                         public void end(String body) {
  9.                                 currentCurrency.setOutcome(body);
  10.                         }
  11.                 });
  12.                
  13.                 root.getChild(MESSAGE).setEndTextElementListener(new EndTextElementListener(){
  14.                         public void end(String body) {
  15.                                 currentCurrency.setMessage(body);
  16.                         }
  17.                 });
  18.  
  19.                 root.getChild(RATE).setEndTextElementListener(new EndTextElementListener(){
  20.                         public void end(String body) {
  21.                                 double rate = Double.parseDouble(body);
  22.                                 currentCurrency.setRate(rate);
  23.                                
  24.                         }
  25.                 });
  26.                
  27.  
  28.                 try {
  29.                         Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
  30.                 } catch (Exception e) {
  31.                         throw new RuntimeException(e);
  32.                 }
  33.                 Log.i("_________________________________", "DONE parsing messages");
  34.                 return currentCurrency;
  35.         }
  36.  
Parsed in 0.040 seconds, using GeSHi 1.0.8.4


Problem solved. It seemed when they have the xmlns="url", you have to put it in for parsing.

So the code would look like this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 final String url = "http://www.xignite.com/services/";
  2.                 RootElement root = new RootElement(url, CROSSRATE);
  3.                 root.getChild(url, OUTCOME).setEndTextElementListener(new EndTextElementListener(){
  4.                         public void end(String body) {
  5.                                 currentCurrency.setOutcome(body);
  6.                         }
  7.                 });
Parsed in 0.037 seconds, using GeSHi 1.0.8.4
Last edited by sourlemon on Fri Dec 18, 2009 7:29 am, edited 2 times in total.
sourlemon
Freshman
Freshman
 
Posts: 3
Joined: Wed Oct 07, 2009 4:06 am

Postby rogerdodger » Fri Dec 04, 2009 5:35 pm

What if u wrap ur xml in a different tag like this...

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <AllCrossRates>
  3.  
  4. <CrossRates>
  5.  
  6.  
  7. </CrossRates>
  8.  
  9. </AllCrossRates>
  10.  
  11.  
Parsed in 0.001 seconds, using GeSHi 1.0.8.4
rogerdodger
Junior Developer
Junior Developer
 
Posts: 21
Joined: Mon Nov 30, 2009 8:38 am

Top

Postby sourlemon » Fri Dec 04, 2009 7:30 pm

I'm downloading the xml file from a website, so I can't control how they generate it.
sourlemon
Freshman
Freshman
 
Posts: 3
Joined: Wed Oct 07, 2009 4:06 am

Postby yamakasi » Mon Dec 14, 2009 12:46 pm

Hi all,i have a problem in that the values that are supposed to be returned to me are either returned as nulls or 0.0. I cannot seem to find the answer so if anyone could help out please do, thank you

Here is the xml:
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <?xml version="1.0" encoding="UTF-8"?>
  3.  
  4.  <gpx creator=""
  5.  
  6.           version="1.1"
  7.  
  8.           xmlns="http://www.topografix.com/GPX/1/1"
  9.  
  10.           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  11.  
  12.           xsi:schemaLocation="http://www.topografix.com/GPX/1/1 gpx.xsd">
  13.  
  14.    <extensions>
  15.  
  16.     <start>Unknown road</start>
  17.  
  18.     <end>Unknown road</end>
  19.  
  20.    </extensions>
  21.  
  22.    <wpt lat="53.38321" lon="-6.60278" />
  23.  
  24.    <wpt lat="53.38323" lon="-6.60280" />
  25.  
  26.    <wpt lat="53.38327" lon="-6.60282" />
  27.  
  28.    <wpt lat="53.38331" lon="-6.60283" />
  29.  
  30.  </gpx>
  31.  
  32.  
Parsed in 0.003 seconds, using GeSHi 1.0.8.4

The values i want to return are the start tag,end tag but most important is to return the wpt lats and lons

Here is the ContentHandler:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package gpx.parser.local;
  3.  
  4.  
  5.  
  6. import java.util.Vector;
  7.  
  8.  
  9.  
  10. import org.xml.sax.Attributes;
  11.  
  12. import org.xml.sax.SAXException;
  13.  
  14. import org.xml.sax.helpers.DefaultHandler;
  15.  
  16.  
  17.  
  18. import gpx.parser.local.ParsedData;
  19.  
  20.  
  21.  
  22. public class ContentHandler extends DefaultHandler
  23.  
  24. {
  25.  
  26.   // Fields
  27.  
  28.   private boolean in_gpx = false;
  29.  
  30.   private boolean in_extensions = false;
  31.  
  32.   //private boolean in_distance = false;
  33.  
  34.   //private boolean in_time = false;
  35.  
  36.   private boolean in_start = false;
  37.  
  38.   private boolean in_end = false;
  39.  
  40.   //private boolean in_rtept = false;
  41.  
  42.   //private boolean in_desc = false;
  43.  
  44.   //private boolean in_offset = false;
  45.  
  46.   //private boolean in_distance_text = false;
  47.  
  48.   //private boolean in_direction = false;
  49.  
  50.   //private boolean in_azimuth = false;
  51.  
  52.   //private boolean in_turn = false;
  53.  
  54.   //private boolean in_turn_angle = false;
  55.  
  56.   //private boolean in_rte = false;
  57.  
  58.   private boolean in_wpt = false;
  59.  
  60.  
  61.  
  62.   private ParsedData myParsedData = new ParsedData();
  63.  
  64.  
  65.  
  66.   // Getter Method
  67.  
  68.   public ParsedData getParsedData()
  69.  
  70.   {
  71.  
  72.         return this.myParsedData;  
  73.  
  74.   }
  75.  
  76.  
  77.  
  78.   public void startDocument() throws SAXException
  79.  
  80.   {
  81.  
  82.         this.myParsedData = new ParsedData();  
  83.  
  84.   }
  85.  
  86.  
  87.  
  88.   public void endDocument() throws SAXException
  89.  
  90.   {
  91.  
  92.         // do nothing  
  93.  
  94.   }
  95.  
  96.  
  97.  
  98.   // Takes care of the opening tags
  99.  
  100.   /** Gets be called on opening tags like:
  101.  
  102.    * <tag>
  103.  
  104.    * Can provide attribute(s), when xml was like:
  105.  
  106.    * <tag attribute="attributeValue">*/
  107.  
  108.   public void startTags(String namespaceURI, String localName,
  109.  
  110.                                                 String qName, Attributes atts) throws SAXException
  111.  
  112.   {
  113.  
  114.         if(localName.equals("gpx"))
  115.  
  116.         {
  117.  
  118.           this.in_gpx = true;  
  119.  
  120.           if(localName.equals("extensions"))
  121.  
  122.           {
  123.  
  124.                   this.in_extensions = true;
  125.  
  126.          
  127.  
  128.           /*else if(localName.equals("distance"))
  129.  
  130.                 {
  131.  
  132.                         this.in_distance = true;       
  133.  
  134.                 }
  135.  
  136.                 else if(localName.equals("time"))
  137.  
  138.                 {
  139.  
  140.                         this.in_time = true;   
  141.  
  142.                 }*/
  143.  
  144.                 if(localName.equals("start"))
  145.  
  146.                 {
  147.  
  148.                         this.in_start = true;  
  149.  
  150.                 }
  151.  
  152.                 else if(localName.equals("end"))
  153.  
  154.                 {
  155.  
  156.                         this.in_end = true;    
  157.  
  158.                 }
  159.  
  160.           }
  161.  
  162.         /*else if(localName.equals("rtept"))
  163.  
  164.         {
  165.  
  166.           this.in_rtept = true;
  167.  
  168.         }
  169.  
  170.         else if(localName.equals("desc"))
  171.  
  172.         {
  173.  
  174.           this.in_desc = true; 
  175.  
  176.         }
  177.  
  178.         else if(localName.equals("offset"))
  179.  
  180.         {
  181.  
  182.           this.in_offset = true;       
  183.  
  184.         }
  185.  
  186.         else if(localName.equals("distance_text"))
  187.  
  188.         {
  189.  
  190.           this.in_distance_text = true;
  191.  
  192.         }
  193.  
  194.         else if(localName.equals("direction"))
  195.  
  196.         {
  197.  
  198.           this.in_direction = true;    
  199.  
  200.         }
  201.  
  202.         else if(localName.equals("azimuth"))
  203.  
  204.         {
  205.  
  206.           this.in_azimuth = true;      
  207.  
  208.         }
  209.  
  210.         else if(localName.equals("turn"))
  211.  
  212.         {
  213.  
  214.           this.in_turn = true; 
  215.  
  216.         }
  217.  
  218.         else if(localName.equals("turn_angle"))
  219.  
  220.         {
  221.  
  222.           this.in_turn_angle = true;   
  223.  
  224.         }*/
  225.  
  226.           else if(localName.equals("wpt"))
  227.  
  228.           {
  229.  
  230.                 String attributeValue = atts.getValue("lat");
  231.  
  232.                 double lat = Double.parseDouble(attributeValue);
  233.  
  234.                 myParsedData.setWpt(lat);
  235.  
  236.          
  237.  
  238.                 String attributeValue2 = atts.getValue("lon");
  239.  
  240.                 double lon = Double.parseDouble(attributeValue2);
  241.  
  242.                 myParsedData.setWpt(lon);
  243.  
  244.           }
  245.  
  246.         }
  247.  
  248.   }
  249.  
  250.  
  251.  
  252.   /** Gets be called on closing tags like:
  253.  
  254.    * </tag> */
  255.  
  256.   public void endTags(String namespaceURI, String localName, String qName)
  257.  
  258.                                                 throws SAXException
  259.  
  260.   {
  261.  
  262.         if(localName.equals("gpx"))
  263.  
  264.         {
  265.  
  266.           this.in_gpx = false;  
  267.  
  268.                
  269.  
  270.           if(localName.equals("extensions"))
  271.  
  272.           {
  273.  
  274.                 this.in_extensions = false;
  275.  
  276.                
  277.  
  278.         /*else if(localName.equals("distance"))
  279.  
  280.         {
  281.  
  282.           this.in_distance = false;    
  283.  
  284.         }
  285.  
  286.         else if(localName.equals("time"))
  287.  
  288.         {
  289.  
  290.           this.in_time = false;
  291.  
  292.         }*/
  293.  
  294.                 if(localName.equals("start"))
  295.  
  296.                 {
  297.  
  298.                   this.in_start = false;       
  299.  
  300.             }
  301.  
  302.             else if(localName.equals("end"))
  303.  
  304.             {
  305.  
  306.                   this.in_end = false; 
  307.  
  308.             }
  309.  
  310.           }
  311.  
  312.         /*else if(localName.equals("rtept"))
  313.  
  314.         {
  315.  
  316.           this.in_rtept = false;       
  317.  
  318.         }
  319.  
  320.         else if(localName.equals("desc"))
  321.  
  322.         {
  323.  
  324.           this.in_desc = false;
  325.  
  326.         }
  327.  
  328.         else if(localName.equals("offset"))
  329.  
  330.         {
  331.  
  332.           this.in_offset = false;      
  333.  
  334.         }
  335.  
  336.         else if(localName.equals("distance_text"))
  337.  
  338.         {
  339.  
  340.           this.in_distance_text = false;       
  341.  
  342.         }
  343.  
  344.         else if(localName.equals("direction"))
  345.  
  346.         {
  347.  
  348.           this.in_direction = false;   
  349.  
  350.         }
  351.  
  352.         else if(localName.equals("azimuth"))
  353.  
  354.         {
  355.  
  356.           this.in_azimuth = false;     
  357.  
  358.         }
  359.  
  360.         else if(localName.equals("turn"))
  361.  
  362.         {
  363.  
  364.           this.in_turn = false;
  365.  
  366.         }
  367.  
  368.         else if(localName.equals("turn_angle"))
  369.  
  370.         {
  371.  
  372.           this.in_turn_angle = false;  
  373.  
  374.         }*/
  375.  
  376.           else if(localName.equals("wpt"))
  377.  
  378.           {
  379.  
  380.                 // Do nothing...
  381.  
  382.           }
  383.  
  384.         }
  385.  
  386.   }
  387.  
  388.  
  389.  
  390.   /** Gets be called on the following structure:
  391.  
  392.    * <tag>characters</tag> */
  393.  
  394.   public void characters(char ch[], int start, int length)
  395.  
  396.   {
  397.  
  398.         if(this.in_start)
  399.  
  400.         {
  401.  
  402.           //myParsedData.setStart(new String(ch, start, length));
  403.  
  404.           myParsedData.setStart(new StringBuffer().append(ch).toString());
  405.  
  406.         }
  407.  
  408.         if(this.in_end)
  409.  
  410.         {
  411.  
  412.           myParsedData.setEnd(new StringBuffer().append(ch).toString());       
  413.  
  414.         }
  415.  
  416.   }
  417.  
  418. }
  419.  
  420.  
Parsed in 0.052 seconds, using GeSHi 1.0.8.4


ParsedData class:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package gpx.parser.local;
  3.  
  4.  
  5.  
  6. public class ParsedData
  7.  
  8. {
  9.  
  10.         //private int distance = 0;
  11.  
  12.         //private int time = 0;
  13.  
  14.         private String start = null;
  15.  
  16.         private String end = null;
  17.  
  18.         //private String desc = null;
  19.  
  20.         //private int offset = 0;
  21.  
  22.         //private int distance_text = 0;
  23.  
  24.         //private String direction = null;
  25.  
  26.         //private double azimuth = 0.0;
  27.  
  28.         //private char turn;
  29.  
  30.         //private double turn_angle;
  31.  
  32.         private double wpt = 0.0;
  33.  
  34.  
  35.  
  36.   /*public int getDistance()
  37.  
  38.   {
  39.  
  40.         return distance;  
  41.  
  42.   }
  43.  
  44.   public void setDistance(int distance)
  45.  
  46.   {
  47.  
  48.         this.distance = distance;
  49.  
  50.   }
  51.  
  52.  
  53.  
  54.   public int getTime()
  55.  
  56.   {
  57.  
  58.         return time;  
  59.  
  60.   }
  61.  
  62.   public void setTime(int time)
  63.  
  64.   {
  65.  
  66.         this.time = time;  
  67.  
  68.   }*/
  69.  
  70.  
  71.  
  72.   public String getStart()
  73.  
  74.   {
  75.  
  76.         return start;  
  77.  
  78.   }
  79.  
  80.   public void setStart(String start)
  81.  
  82.   {
  83.  
  84.         this.start = start;  
  85.  
  86.   }
  87.  
  88.  
  89.  
  90.   public String getEnd()
  91.  
  92.   {
  93.  
  94.         return end;  
  95.  
  96.   }
  97.  
  98.   public void setEnd(String end)
  99.  
  100.   {
  101.  
  102.         this.end = end;
  103.  
  104.   }
  105.  
  106.  
  107.  
  108.   /*public String getDesc()
  109.  
  110.   {
  111.  
  112.         return desc;  
  113.  
  114.   }
  115.  
  116.   public void setDesc(String desc)
  117.  
  118.   {
  119.  
  120.         this.desc = desc;  
  121.  
  122.   }
  123.  
  124.  
  125.  
  126.   public int getOffset()
  127.  
  128.   {
  129.  
  130.         return offset;  
  131.  
  132.   }
  133.  
  134.   public void setOffset(int offset)
  135.  
  136.   {
  137.  
  138.         this.offset = offset;  
  139.  
  140.   }*/
  141.  
  142.  
  143.  
  144.   /*public int getDistanceText()
  145.  
  146.   {
  147.  
  148.         return distance_text;  
  149.  
  150.   }
  151.  
  152.   public void setDistanceText(int distance_text)
  153.  
  154.   {
  155.  
  156.         this.distance_text = distance_text;  
  157.  
  158.   }*/
  159.  
  160.  
  161.  
  162.   /*public String getDirection()
  163.  
  164.   {
  165.  
  166.         return direction;  
  167.  
  168.   }
  169.  
  170.   public void setDirection(String direction)
  171.  
  172.   {
  173.  
  174.         this.direction = direction;  
  175.  
  176.   }
  177.  
  178.  
  179.  
  180.   public double getAzimuth()
  181.  
  182.   {
  183.  
  184.         return azimuth;  
  185.  
  186.   }
  187.  
  188.   public void setAzimtuh(double azimuth)
  189.  
  190.   {
  191.  
  192.         this.azimuth = azimuth;  
  193.  
  194.   }*/
  195.  
  196.  
  197.  
  198.   /*public char getTurn()
  199.  
  200.   {
  201.  
  202.         return turn;  
  203.  
  204.   }
  205.  
  206.   public void setTurn(char turn)
  207.  
  208.   {
  209.  
  210.         this.turn = turn;  
  211.  
  212.   }*/
  213.  
  214.  
  215.  
  216.   /*public double getTurnAngle()
  217.  
  218.   {
  219.  
  220.         return turn_angle;  
  221.  
  222.   }
  223.  
  224.   public void setTurnAngle(double turn_angle)
  225.  
  226.   {
  227.  
  228.         this.turn_angle = turn_angle;  
  229.  
  230.   }*/
  231.  
  232.  
  233.  
  234.   public double getWpt()
  235.  
  236.   {
  237.  
  238.         return wpt;  
  239.  
  240.   }
  241.  
  242.   public void setWpt(double wpt)
  243.  
  244.   {
  245.  
  246.         this.wpt = wpt;  
  247.  
  248.   }
  249.  
  250.  
  251.  
  252.   public String toString()
  253.  
  254.   {
  255.  
  256.         return //"Extracted Distance: " + this.distance
  257.  
  258.                         //+ "\nExtracted Time: " + this.time
  259.  
  260.                         "\nExtracted Start: " + this.start
  261.  
  262.                         + "\nExtracted End: " + this.end
  263.  
  264.                         //+ "\nExtracted Desc: " + this.desc
  265.  
  266.                         //+ "\nExtracted Offset: " + this.offset
  267.  
  268.                         //+ "\nExtracted Distance Text: " + this.distance_text
  269.  
  270.                         //+ "\nExtracted Direction: " + this.direction
  271.  
  272.                         //+ "\nExtracted Azimuth: " + this.azimuth
  273.  
  274.                         //+ "\nExtracted Turn: " + this.turn
  275.  
  276.                         //+ "\nExtracted Turn Angle: " + this.turn_angle
  277.  
  278.                         + "\nExtracted Waypoints: " + this.wpt;
  279.  
  280.   }
  281.  
  282. }
  283.  
  284.  
Parsed in 0.043 seconds, using GeSHi 1.0.8.4


Main class GPXParserLocal:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package gpx.parser.local;
  3.  
  4.  
  5.  
  6. import java.io.BufferedReader;
  7.  
  8. import java.io.FileInputStream;
  9.  
  10. import java.io.InputStream;
  11.  
  12. import java.io.InputStreamReader;
  13.  
  14. import java.util.Vector;
  15.  
  16.  
  17.  
  18. import javax.xml.parsers.SAXParser;
  19.  
  20. import javax.xml.parsers.SAXParserFactory;
  21.  
  22.  
  23.  
  24. import org.xml.sax.InputSource;
  25.  
  26. import org.xml.sax.SAXException;
  27.  
  28. import org.xml.sax.XMLReader;
  29.  
  30.  
  31.  
  32. import gpx.parser.local.ContentHandler;
  33.  
  34. import gpx.parser.local.ParsedData;
  35.  
  36.  
  37.  
  38. import gpx.parser.local.ContentHandler;
  39.  
  40. import gpx.parser.local.ParsedData;
  41.  
  42.  
  43.  
  44. import gpx.parser.local.R;
  45.  
  46.  
  47.  
  48. import android.app.Activity;
  49.  
  50. import android.content.Context;
  51.  
  52. import android.os.Bundle;
  53.  
  54. import android.view.View;
  55.  
  56. import android.widget.Button;
  57.  
  58. import android.widget.TextView;
  59.  
  60.  
  61.  
  62. public class GPXParserLocal extends Activity {
  63.  
  64.         private TextView orgXml;
  65.  
  66.         private TextView parsedXml;
  67.  
  68.         private Button parseButton;
  69.  
  70.  
  71.  
  72.         /** Called when the activity is first created. */
  73.  
  74.         @Override
  75.  
  76.         public void onCreate(Bundle savedInstanceState)
  77.  
  78.         {
  79.  
  80.           super.onCreate(savedInstanceState);
  81.  
  82.  
  83.  
  84.           try
  85.  
  86.           {
  87.  
  88.                 setContentView(R.layout.main);
  89.  
  90.                 orgXml = (TextView) findViewById(R.id.orgXMLTxt);
  91.  
  92.                 parsedXml = (TextView) findViewById(R.id.parsedXMLTxt);
  93.  
  94.                 parseButton = (Button) findViewById(R.id.parseBtn);
  95.  
  96.  
  97.  
  98.                 orgXml.setText(getOriginalXML());
  99.  
  100.                 parseButton.setOnClickListener(new View.OnClickListener()
  101.  
  102.                 {
  103.  
  104.  
  105.  
  106.               public void onClick(View v)
  107.  
  108.               {
  109.  
  110.                     try
  111.  
  112.                     {
  113.  
  114.                   parsedXml.setText(getParsedXML());
  115.  
  116.                     }
  117.  
  118.                     catch (Exception e)
  119.  
  120.                     {
  121.  
  122.                       orgXml.setText(e.getMessage());
  123.  
  124.                     }
  125.  
  126.                   }
  127.  
  128.             });
  129.  
  130.           }
  131.  
  132.           catch (Exception e)
  133.  
  134.           {
  135.  
  136.                 orgXml.setText(e.getMessage());
  137.  
  138.           }
  139.  
  140.  
  141.  
  142.         }
  143.  
  144.  
  145.  
  146.         private String getOriginalXML() throws Exception {
  147.  
  148.                 FileInputStream in = new FileInputStream("/sdcard/foot.xml");
  149.  
  150.                 StringBuffer inLine = new StringBuffer();
  151.  
  152.                 InputStreamReader isr = new InputStreamReader(in);
  153.  
  154.  
  155.  
  156.                 BufferedReader inRd = new BufferedReader(isr);
  157.  
  158.  
  159.  
  160.                 String text;
  161.  
  162.                 while ((text = inRd.readLine()) != null) {
  163.  
  164.                         inLine.append(text);
  165.  
  166.                         inLine.append("\n");
  167.  
  168.                 }
  169.  
  170.                 in.close();
  171.  
  172.                 return inLine.toString();
  173.  
  174.         }
  175.  
  176.  
  177.  
  178.         private String getParsedXML() throws Exception {
  179.  
  180.                 StringBuffer inLine = new StringBuffer();
  181.  
  182.                 /* Get a SAXParser from the SAXPArserFactory. */
  183.  
  184.                 SAXParserFactory spf = SAXParserFactory.newInstance();
  185.  
  186.                 SAXParser sp = spf.newSAXParser();
  187.  
  188.  
  189.  
  190.                 /* Get the XMLReader of the SAXParser we created. */
  191.  
  192.                 XMLReader xr = sp.getXMLReader();
  193.  
  194.                 /* Create a new ContentHandler and apply it to the XML-Reader */
  195.  
  196.                 ContentHandler myContentHandler = new ContentHandler();
  197.  
  198.                 xr.setContentHandler(myContentHandler);
  199.  
  200.  
  201.  
  202.                 FileInputStream in = new FileInputStream("/sdcard/foot.xml");
  203.  
  204.  
  205.  
  206.                 xr.parse(new InputSource(in));
  207.  
  208.                 ParsedData myParsedData = myContentHandler.getParsedData();
  209.  
  210.                 inLine.append(myParsedData.toString());
  211.  
  212.                 in.close();
  213.  
  214.                 return inLine.toString();
  215.  
  216.         }
  217.  
  218. }
  219.  
  220.  
Parsed in 0.049 seconds, using GeSHi 1.0.8.4


A BIG THANK YOU to everyone who helps out
yamakasi
Freshman
Freshman
 
Posts: 3
Joined: Wed Oct 21, 2009 10:26 am
Location: Ireland

Postby padde » Tue Dec 15, 2009 5:53 am

Here ya go...

XmlContentHandler.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.padde.xmldemo;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. import org.xml.sax.Attributes;
  6. import org.xml.sax.SAXException;
  7. import org.xml.sax.helpers.DefaultHandler;
  8.  
  9. class Waypoint {
  10.         public double lat;
  11.         public double lon;
  12.        
  13.         public Waypoint(double lat, double lon) {
  14.                 this.lat = lat;
  15.                 this.lon = lon;
  16.         }
  17. }
  18.  
  19. class Gpx {
  20.         private String start;
  21.         private String end;
  22.         private ArrayList<Waypoint> waypoints;
  23.                
  24.         public Gpx() { waypoints = new ArrayList<Waypoint>(); }
  25.        
  26.         public void setStart(String str) { this.start = str; }
  27.         public void setEnd(String str) { this.end = str; }
  28.         public void addWaypoint(double lat, double lon) { waypoints.add(new Waypoint(lat,lon)); }
  29.        
  30.         public String getStart() { return this.start; }
  31.         public String getEnd() { return this.end; }
  32.         public Waypoint getWaypointAt(int i) { return waypoints.get(i); }
  33.         public ArrayList<Waypoint> getWaypoints() { return waypoints; }
  34. }
  35.  
  36. public class XmlContentHandler extends DefaultHandler {
  37.     enum XML_TAGS { gpx, extensions, start, end, wpt }
  38.     boolean in_staTag = false;
  39.     boolean in_endTag = false;
  40.    
  41.     Gpx mygpx = null;
  42.    
  43.     public Gpx returnResults() { return (mygpx != null)? mygpx : null; }
  44.    
  45.     public void startDocument() throws SAXException { }
  46.     public void endDocument() throws SAXException { }
  47.  
  48.     public void startElement(String ns, String ln, String qn, Attributes at) throws SAXException {
  49.         switch(XML_TAGS.valueOf(ln)) {
  50.                 case gpx:
  51.                         mygpx = new Gpx();
  52.                         break;
  53.                 case start:
  54.                         in_staTag = true;
  55.                         break;
  56.                 case end:
  57.                         in_endTag = true;
  58.                         break;
  59.                 case wpt:
  60.                         if(mygpx != null)
  61.                                 mygpx.addWaypoint( Double.parseDouble(at.getValue("lat")),
  62.                                        Double.parseDouble(at.getValue("lon")) );
  63.                         break;
  64.                 default: break;
  65.         }
  66.     }
  67.  
  68.     public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
  69.         switch(XML_TAGS.valueOf(localName)) {
  70.                 case start:
  71.                         in_staTag = false;
  72.                         break;
  73.                 case end:
  74.                         in_endTag = false;
  75.                         break;
  76.                 default: break;
  77.         }
  78.     }
  79.      
  80.     public void characters(char ch[], int start, int length) {
  81.         if(in_staTag) mygpx.setStart(new String(ch,start,length));
  82.         if(in_endTag) mygpx.setEnd(new String(ch,start,length));
  83.     }
  84. }
  85.  
Parsed in 0.047 seconds, using GeSHi 1.0.8.4


XmlReader.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.padde.xmldemo;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  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.InputSource;
  11. import org.xml.sax.SAXException;
  12. import org.xml.sax.XMLReader;
  13.  
  14. public class XmlReader {
  15.     public static Gpx read(InputStream in) {
  16.         SAXParserFactory spf = SAXParserFactory.newInstance();
  17.         SAXParser sp;
  18.         try {
  19.             sp = spf.newSAXParser();
  20.             XMLReader xr = sp.getXMLReader();
  21.             XmlContentHandler ach = new XmlContentHandler();
  22.             xr.setContentHandler(ach);
  23.             xr.parse(new InputSource(in));
  24.             return ach.returnResults();
  25.         } catch (ParserConfigurationException e) {
  26.         } catch (SAXException e) {
  27.         } catch (IOException e) {}
  28.         return null;
  29.     }
  30. }
  31.  
Parsed in 0.040 seconds, using GeSHi 1.0.8.4


XmlDemo.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.padde.xmldemo;
  2.  
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5.  
  6. public class XmlDemo extends Activity {
  7.  
  8.     public void onCreate(Bundle savedInstanceState) {
  9.           super.onCreate(savedInstanceState);
  10.           setContentView(R.layout.main);
  11.      
  12.           Gpx test = XmlReader.read(this.getResources().openRawResource(R.raw.test));
  13.          
  14.           if(test != null) {
  15.               System.out.println("Start: "+test.getStart());
  16.               System.out.println("End:   "+test.getEnd());
  17.        
  18.               for(Waypoint blub : test.getWaypoints())
  19.                   System.out.println("lat: "+blub.lat+" lon: "+blub.lon);
  20.           }
  21.     }
  22. }
  23.  
Parsed in 0.039 seconds, using GeSHi 1.0.8.4
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

SAX Parser Problem

Postby student_ct » Tue Dec 15, 2009 11:39 am

I have a problem and i don't know if it's because the xml file has similar tags.
I want to get the datas from the site:
http://www.cbssports.com/partners/feeds/isg/scores
but only the NHL datas.
Here's my Code:
ExampleHandler.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package xml.test.ch;
  2.  
  3. import org.xml.sax.Attributes;
  4. import org.xml.sax.SAXException;
  5. import org.xml.sax.helpers.DefaultHandler;
  6.  
  7. public class ExampleHandler extends DefaultHandler{
  8.        
  9.  
  10.     // ===========================================================
  11.     // Fields
  12.     // ===========================================================
  13.    
  14.     private boolean scores = false;
  15.     private boolean league_scores = false;
  16.     private boolean game = false;
  17.     private boolean venue = false;
  18.     private boolean game_team = false;
  19.    
  20.     public String score;
  21.     public String name;
  22.     public String attrValue;
  23.    
  24.     private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
  25.  
  26.     // ===========================================================
  27.     // Getter & Setter
  28.     // ===========================================================
  29.  
  30.     public ParsedExampleDataSet getParsedData() {
  31.          return this.myParsedExampleDataSet;
  32.     }
  33.  
  34.     // ===========================================================
  35.     // Methods
  36.     // ===========================================================
  37.     @Override
  38.     public void startDocument() throws SAXException {
  39.          this.myParsedExampleDataSet = new ParsedExampleDataSet();
  40.     }
  41.  
  42.     @Override
  43.     public void endDocument() throws SAXException {
  44.          // Nothing to do
  45.     }
  46.  
  47.     /** Gets be called on opening tags like:
  48.      * <tag>
  49.      * Can provide attribute(s), when xml was like:
  50.      * <tag attribute="attributeValue">*/
  51.     @Override
  52.     public void startElement(String namespaceURI, String localName,
  53.               String qName, Attributes atts) throws SAXException {
  54.                 if(localName.equals("scores"))
  55.                 {
  56.                         if(localName.equals("league_scores")){
  57.                                 // Extract an Attribute
  58.                           attrValue = atts.getValue("league_abbr");
  59.                         }
  60.              
  61.                         if(attrValue.equals("NHL"))
  62.                         {
  63.                                 if(localName.equals("game_team"))
  64.                                 {
  65.                                         score = atts.getValue("score");
  66.                                         int i = Integer.parseInt(score);
  67.                                         myParsedExampleDataSet.setExtractedInt(i);
  68.                                        
  69.                                 }      
  70.                         }
  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.          
  80.     }
  81.    
  82.     /** Gets be called on the following structure:
  83.      * <tag>characters</tag> */
  84.     @Override
  85.    public void characters(char ch[], int start, int length) {
  86.         // myParsedExampleDataSet.setExtractedString(new String(ch, start, length));
  87.    }
  88. }
  89.  
  90.  
Parsed in 0.046 seconds, using GeSHi 1.0.8.4


Please Help.
student_ct
Freshman
Freshman
 
Posts: 2
Joined: Mon Dec 14, 2009 10:04 am

Postby nitemovz » Sun Dec 20, 2009 3:03 am

I get an error when I try to run the code that has been written from this tutorial.

The exact error is:
Error: Permission denied (maybe missing INTERNET permission)


How do I fix this?!
nitemovz
Junior Developer
Junior Developer
 
Posts: 11
Joined: Sat Dec 19, 2009 6:44 pm

Postby padde » Sun Dec 20, 2009 9:19 am

1. read the error message.. it says loud and clear what to do
2. use th damn search function

If you cant fix your "problem" after those 2 steps...

1. throw away your phone
2. search a different hobby.. coding isnt the right one for you
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby achie1266 » Sun Dec 20, 2009 9:30 am

lol Padde looks pissed off, It seems that you did not even bother reading the tutorials or searching on the web for your error.
anyway coming to your error it is because your application does not have permission to connect to the internet by default. You have to allow it to do so.
we do it by allowing it to connect to the internet in this way
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <uses-permission android:name="android.permission.INTERNET" />
Parsed in 0.000 seconds, using GeSHi 1.0.8.4
you should add this in your manifest file. I too had this problem too a month back when I started developing on android but the documentation and searching on web solved my problem.
achie
User avatar
achie1266
Master Developer
Master Developer
 
Posts: 223
Joined: Mon Nov 09, 2009 10:56 pm
Location: Denver

XML Parser

Postby matrix » Tue Dec 22, 2009 5:37 am

I think this is a great write up thank you. I for some reason in the example I only get the integer returned. I do not know why I am having so much trouble with this. I also tried putting 2 entries and only the last one showed up. Is there a loop for this I am missing. I am used to web development and am wanting to make basically an RSS reader - I want to get a list and one of the xml filed contains the url to the master data record where I could pull the xml file for that. Make any since and/or is there a beetter more appropriate way - Like querying a mssql or mysql db directly.
matrix
Freshman
Freshman
 
Posts: 4
Joined: Tue Dec 22, 2009 5:07 am
Location: IN

How To Handle this structure

Postby nmorrisii » Tue Dec 29, 2009 3:58 pm

I am on day 4 of examining the API, however, I am still struggling how to parse this xml example. I followed the example in this thread, but my xml structure has the following...
<RESULTS>
<ROW>
<COLUMN columnnumber="1" name="ID">
<text>054686CFABEDFE0E8525768D006B2AA4</text>
</COLUMN>
<COLUMN columnnumber="6" name="CATEGORY">
<text>Day 1 - Sunday</text>
</COLUMN>
</ROW>
</RESULTS>

I am trying to get the value of the child node "text"

I'll keep reading, but if someone can provide a clue, it will help.
nmorrisii
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Dec 29, 2009 3:51 pm

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 4 guests