Friday, August 24, 2012

ANDROID XML PARSER PART 2




SAX Parser:
SAX stands for Simple API for XML. It uses a "push" approach: whereas with DOM you can dig around in the document in whatever order you like, SAX parsing is event-driven which means you have to handle the data as it is given to you.

SAX parsers fire events when they encounter the various components that make up an XML file. You register a ContentHandler whose methods are called-back when these events occur (for example when the parser finds a new start element, it invokes the startElement method of yourContentHandler).

The API assumes that the consumer (ContentHandler) is going to maintain some awareness of its state (e.g. where it currently is within the document). I sometimes use a java.util.Stack to push/pop/peek at which element I'm currently working in, but here I can get away with just recording the name of the current element.

I'm extending DefaultHandler because I'm not interested in many of the events (it provides a default empty implementation of those methods for me).

SOME KEYS POINTS:


·        A SAX (Simple API for XML) parser does not create any internal structure. Instead, it takes the occurrences of components of an input document as events, and tells the client what it reads as it reads through the input document.
·        A SAX parser serves the client application always only with pieces of the document at any given time.
·        A SAX parser, however, is much more space efficient in case of a big input document (because it creates no internal structure). What’s more, it runs faster and is easier to learn than DOM parser because its API is really simple. But from the functionality point of view, it provides a fewer functions, which means that the users themselves have to take care of more, such as creating their own data structures.

SAX:
  1. Parses node by node
  2. Doesnt store the XML in memory
  3. We cant insert or delete a node
  4. Top to bottom traversing.

Sequence of events It doesn't use any memory preferred for large documents. Faster at runtime, because of the above mentioned point. Objects are to be created. Need to write code for creating objects In SAX Backward navigation is not possible as it sequentially processes the document
So if you have very large files then you should use SAX parser since it will fire events and releasing them ,nothing is stored in memory ,and using SAX parser you can't access element in a random way there is no going back ! , but Dom let you access any part of the xml file since it keeps the whole file/document in memory

EXAMPLE CODE:
SOURCE CODE IS HERE :  DOWNLOAD


















No comments:

Post a Comment