Parsing an XML document using android's SAXParser libraries..

 You have to parse the inputstream of the sample.xml  from the another java program..or you can do within the below java file too.[in parse(...) method]

All the data are put in a ArrayList of Feed class. you can have access to it once parsing is done.

3 overriden methods to be focused are:
1)      startElement()
2)      endElement()
3)      characters()

Rest of the code is self explanatory and hope you would be interested in code than paragraphs :P

============= Java file =======================
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;


/**
 *
 * @author chandan,Jun 22, 2013,11:26:05 AM
 */
public class Parser extends DefaultHandler {

      private static final String TAG = Parser.class.getSimpleName();
     
    private Feed feed;
    private StringBuilder text;
    private Item item;

    /**
     * Default constructor.
     *
     * chandan,Jun 22, 2013,11:32:05 AM
     */
    public Parser() {
      //Intialize here.
        this.text = new StringBuilder();
    }

    /**
     * Call this method with stream to parse.
     * @param urlInputStream
     * chandan,Jun 22, 2013,11:27:04 AM
     */
    public void parse(InputStream urlInputStream) {

        SAXParserFactory spf = null;
        SAXParser sp = null;

        try {

            spf = SAXParserFactory.newInstance();
            if (spf != null)
             {
                sp = spf.newSAXParser();
                sp.parse(urlInputStream, this);
             }
        }
        catch (Exception e)
        {          
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (urlInputStream != null)
                    urlInputStream.close();

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * use this method to get an instance of the Feed to
     *  access the ArrayList which holds parsed data
     * @return Feed
     */
    public Feed getFeed() {
        return (this.feed);

    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) {
        if (qName.equalsIgnoreCase("root")) {
            this.feed = new Feed();
        }

        else if (qName.equalsIgnoreCase("item") && (this.feed != null)) {
            this.item = new Item();
            this.feed.addItem(this.item);
        }

        // if a TAG has one or more than one attribute, then..
        int attLength = attributes.getLength();
        if (attLength > 0) {

            for (int i = 0; i < attLength; i++) {

                String attName = attributes.getLocalName(i);
                String attValue = attributes.getValue(i);
               
            
                if (attName.equalsIgnoreCase("value")&& this.item.subheaderCount< 2)
                {
                    this.item.subheaderCount++;
                    this.item.lists.put("subheader "+ this.item.subheaderCount,attValue);
                }
              
                else if (attName.equalsIgnoreCase("attribute2") && attValue.equalsIgnoreCase("yes"))
                {                                    
                    this.item.lists.put("attribute2", attributes.getValue(i));
                   /*
                            for previous attribute: attributes.getValue(i-1)
                    */
                }

            }// End of for loop
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) {

        if (this.feed == null) {
            return;
        }

        if (qName.equalsIgnoreCase("item")){
            this.item = null;
        }else if (qName.equalsIgnoreCase("header")) {
            if (this.item != null){
                this.item.lists.put("header", this.text.toString().trim());
            }
        }       
       
        //Finally reset text's length
        this.text.setLength(0);
    }

    @Override
    public void characters(char[] ch, int start, int length) {
        this.text.append(ch, start, length);
    }
   
    /**
     * Model class for Feed.
     *
     * @author chandan,Jun 22, 2013,11:30:33 AM
     */
    public static class Feed {
       
        /* You can make public so that you can access directly upon parsing..*/
        private ArrayList<Item> items;

        public void addItem(Item item) {
            if (this.getItems() == null)
                this.setItems(new ArrayList<Item>());
            this.getItems().add(item);
        }

        public void setItems(ArrayList<Item> items) {
            this.items = items;
        }

        public ArrayList<Item> getItems() {
            return items;
        }

    }
   
    /**
     * Model class for Item.
     *
     * @author chandan,Jun 22, 2013,11:30:25 AM
     */
    public static class Item {
     
        public int subheaderCount;
            public Hashtable lists = new Hashtable();
        public static int optionCount;

     
        Item() {
            optionCount = 0;
            lists.put("header", new String());
            /*  for integer...Do not forget to parse from string to int--->lists.put("intData", new Integer(0));   */
            lists.put("subheader 1", new String());
            lists.put("subheader 2", new String());
           
            lists.put("attribute2", new String());

        }

    }
}

============== sample.xml file  ==================


<root>
            <item>
                      <header>Your header here..</header>  
                           <subheader value="1st subheader value here ">
                           </subheader >
                           <subheader value="2nd subheader vslue here" attribute2="yes">
                           </subheader >
           </item>
           <item>
            .
            .
            .
            .
          </item>
.
.
.
.
</root>

=============== End  =======================

Happy coding :)

No comments:

Post a Comment