SaxXmlParser.java - SAX XML Parser Example

Q

How to parse an XML file with SAX (Simple API for XML) API?

✍: FYIcenter

A

If you want to parse an XML file with SAX (Simple API for XML), you can these suggestions privded below:

1. Use the factory class to create SAXParser object:

      SAXParserFactory f = SAXParserFactory.newInstance();
      SAXParser p = f.newSAXParser();

2. Extend the DefaultHandler class to replace default event handlers with your logics:

  • startElement() - Called when the parser finishes reading the starting tag of an XML element.
  • endElement() - Called when the parser finishes reading the ending tag of an XML element.
  • characters() - Called when the parser finishes reading a chunk of text content of an XML element.
  • more...

3. Call the parse() method on the Parser object to parse an XML file with an object that has your own event handlers:

	  p.parse(new File(args[0]), new SaxXmlParser());

Here is a complete example of parsing an XML file with SAX API, SaxXmlParser.java:

// Copyright (c) 2017 FYIcenter.com
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import java.io.*;

public class SaxXmlParser extends DefaultHandler {
   static String dot = "............................................................";
   static int l = 0;
   public static void main(String[] args) throws Exception {
      SAXParserFactory f = SAXParserFactory.newInstance();
      SAXParser p = f.newSAXParser();
      System.out.println("Parser class: "+p.getClass().getName());
	  
	  p.parse(new File(args[0]), new SaxXmlParser());
   }
   public void startElement(String uri, String lName, String qName, Attributes atts) {
      l++;
      System.out.print("\n"+dot.substring(0,l)+lName+qName);
   }
   public void endElement(String uri, String lName, String qName) {
      l--;
   }
   public void characters(char[] ch, int start, int length) {
      System.out.print("("+(new String(ch,start,length))+")");
   }
}

Compile and run the example program, SaxXmlParser.java:

>\fyicenter\jdk-1.8.0\bin\javac SaxXmlParser.java

>\fyicenter\jdk-1.8.0\bin\java SaxXmlParser UserCompact.xml

Parser class: com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl

.User
..ID(101)
..BirthDate(1970-01-01+00:01)
..Name(Frank Y. Ivy)
..Sex(  Male)

Here is the XML file, UserCompact.xml, used in the above example:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<User><ID>101</ID><BirthDate>1970-01-01+00:01</BirthDate><Name>Frank Y. Ivy</Name><Sex>  Male</Sex></User>

 

Using XML SAX API with Apache Xerces

⇒⇒FAQ for Apache Xerces XML Parser

2017-12-09, 340👍, 0💬