Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing local XML file using Sax in Android

Can anyone tell me how to parse a local XML file stored in the system using SAX, with an example code? Please also tell me where can I find information on that.

like image 396
apoorva Avatar asked Apr 28 '10 09:04

apoorva


People also ask

How do you use a SAX parser?

SAX parser methods to override The important methods to override are startElement() , endElement() and characters() . SAXParser starts parsing the document, when any start element is found, startElement() method is called. We are overriding this method to set boolean variables that will be used to identify the element.

What is XML parsing in Android?

Android DOM(Document Object Model) parser is a program that parses an XML document and extracts the required information from it. This parser uses an object-based approach for creating and parsing the XML files.

Which method does SAX use for processing XML documents?

The Simple API for XML (SAX) is an event-based API that uses callback routines or event handlers to process different parts of an XML documents. To use SAX, one needs to register handlers for different events and then parse the document.

What is DOM and SAX in XML?

DOM is a tree-based interface that models an XML doc- ument as a tree of nodes, via which an application can search for nodes, read their information, and update the contents of the nodes. SAX is an event-driven interface. The application registers with the parser various event handlers.


2 Answers

To read from XML in your app, create a folder in your res folder inside your project called "xml" (lower case). Store your xml in this newly created folder. To load the XML from your resources,

XmlResourceParser myxml = mContext.getResources().getXml(R.xml.MyXml);//MyXml.xml is name of our xml in newly created xml folder, mContext is the current context
// Alternatively use: XmlResourceParser myxml = getContext().getResources().getXml(R.xml.MyXml);

myxml.next();//Get next parse event
int eventType = myxml.getEventType(); //Get current xml event i.e., START_DOCUMENT etc.

You can then start to process nodes, attributes etc and text contained within by casing the event type, once processed call myxml.next() to get the next event, i.e.,

 String NodeValue;
    while (eventType != XmlPullParser.END_DOCUMENT)  //Keep going until end of xml document
    {  
        if(eventType == XmlPullParser.START_DOCUMENT)   
        {     
            //Start of XML, can check this with myxml.getName() in Log, see if your xml has read successfully
        }    
        else if(eventType == XmlPullParser.START_TAG)   
        {     
            NodeValue = myxml.getName();//Start of a Node
            if (NodeValue.equalsIgnoreCase("FirstNodeNameType"))
            {
                    // use myxml.getAttributeValue(x); where x is the number
                    // of the attribute whose data you want to use for this node

            }

            if (NodeValue.equalsIgnoreCase("SecondNodeNameType"))
            {
                    // use myxml.getAttributeValue(x); where x is the number
                    // of the attribute whose data you want to use for this node

            } 
           //etc for each node name
       }   
        else if(eventType == XmlPullParser.END_TAG)   
        {     
            //End of document
        }    
        else if(eventType == XmlPullParser.TEXT)   
        {    
            //Any XML text
        }

        eventType = myxml.next(); //Get next event from xml parser
    }
like image 51
Steven Avatar answered Oct 12 '22 11:10

Steven


package com.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import android.widget.Toast;

public class FeedHandler extends DefaultHandler {

    StringBuilder sb = null;
    String ret = "";
    boolean bStore = false;
    int howMany = 0;

    FeedHandler() {   }

    String getResults()
    {
        return "XML parsed data.\nThere are [" + howMany + "] status updates\n\n" + ret;
    }
    @Override
    public void startDocument() throws SAXException 
    {
        // initialize "list"
    }

    @Override
    public void endDocument() throws SAXException
    {

    }

    @Override
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {

        try {
            if (localName.equals("status"))
            {
                this.sb = new StringBuilder("");
                bStore = true;
            }
            if (localName.equals("user")) 
            {
                bStore = false;
            }
            if (localName.equals("text")) 
            {
                this.sb = new StringBuilder("");
                Log.i("sb ", sb+"");

            }
            if (localName.equals("created_at")) 
            {
                this.sb = new StringBuilder("");
            }
        } catch (Exception e) 
        {

            Log.d("error in startElement", e.getStackTrace().toString());
        }
    }
    @Override

    public void endElement(String namespaceURI, String localName, String qName) throws SAXException 
    {

        if (bStore) 
        {
            if (localName.equals("created_at"))
            {
                ret += "Date: " + sb.toString() + "\n"; 
                sb = new StringBuilder("");
                return;

            }

            if (localName.equals("user"))
            {
                bStore = true;
            }

            if (localName.equals("text")) 
            {

                ret += "Post: " + sb.toString() + "\n\n";
                sb = new StringBuilder("");
                return;

            }


        }
        if (localName.equals("status"))
        {
            howMany++;
            bStore = false;
        }
    }
    @Override

    public void characters(char ch[], int start, int length)
    {

        if (bStore) 
        {
//          System.out.println("start " +start+"length "+length);
            String theString = new String(ch, start, length);

            this.sb.append(theString+"start "+start+" length "+length);
        }
    }

}
InputSource is = new InputSource(getResources().openRawResource(R.raw.my));
                System.out.println("running xml file..... ");
            // create the factory
            SAXParserFactory factory = SAXParserFactory.newInstance();

            // create a parser
            SAXParser parser = factory.newSAXParser();

            // create the reader (scanner)
            XMLReader xmlreader = parser.getXMLReader();

            // instantiate our handler
            FeedHandler fh = new FeedHandler();

            // assign our handler
            xmlreader.setContentHandler(fh);

            // perform the synchronous parse
            xmlreader.parse(is);

            // should be done... let's display our results
            tvData.setText(fh.getResults());
like image 25
Pragna Avatar answered Oct 12 '22 11:10

Pragna