• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 324
  • Last Modified:

SAX PARSER - Using TAG for parsing.....


Can I use Sax Parser to parse the file using Tag Name, as we do in case of DOM Parser?

If this is possible then how to get all the elements Name and the corresponding values.

A sample code would be very welcome.


  • 2
2 Solutions
mickey_lovelyAuthor Commented:
The link that CE gave was for parsing the file.

The thing I wanted is that can I parse the file on the basis of tags, like we do in case of DOM by using getValueByTagName() method.
Can we do similar thing in case of SAX. Can we use the same method or any similar thing?
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.apache.xerces.parsers.SAXParser;

public class Flour extends DefaultHandler {

  float amount = 0;

  public void startElement(String namespaceURI, String localName,
                           String qName, Attributes atts) {
    if (namespaceURI.equals("http://recipes.org") && localName.equals("ingredient")) {
       String n = atts.getValue("","name");
       if (n.equals("flour")) {
         String a = atts.getValue("","amount"); // assume 'amount' exists
         amount = amount + Float.valueOf(a).floatValue();

  public static void main(String[] args) {
    Flour f = new Flour();
    SAXParser p = new SAXParser();
    try { p.parse(args[0]); }
    catch (Exception e) {e.printStackTrace();}

Look at: http://www.saxproject.org/quickstart.html
it is a short and quick tutorial to SAX that uses your needs (extract / printout) the name of elements and content
as its example (source code is embeded in that page)

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now