Javax.xml.parsers.SAXParser.parse() Method



Description

The Javax.xml.parsers.SAXParser.parse(InputStream is, HandlerBase hb, String systemId) method parses the content InputStream instance as XML using the specified HandlerBase.

Declaration

Following is the declaration for Javax.xml.parsers.SAXParser.parse() method

public void parse(InputStream is, HandlerBase hb, String systemId)

Parameters

  • is − The InputStream containing the content to be parsed.

  • hb − The SAX HandlerBase to use.

  • systemId − The systemId which is needed for resolving relative URIs.

Return Value

This method does not return a value.

Exception

  • IllegalArgumentException − If the InputStream object is null

  • IOException − If any IO errors occur.

  • SAXException − If any SAX errors occur during processing.

Example

For our examples to work, a xml file named Student.xml is needed in our CLASSPATH. The contents of this XML are the following:

<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?>
<student id = "10">
   <age>12</age>
   <name>Malik</name>
</student>

The following example shows the usage of Javax.xml.parsers.SAXParser.parse() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.HandlerBase;

public class SaxParserDemo {

   public static void main(String[] args) {

      // create a new SAXParserFactory
      SAXParserFactory factory = SAXParserFactory.newInstance();

      // create a new DefaultHandler
      HandlerBase handler = new HandlerBase() {

         // define what the parser does when it finds a character
         public void characters(char[] ch, int start, int length) {

            // print the characters
            System.out.println("" + new String(ch, start, length));
         }
      };

      try {

         // create a new inputstream for our XML
         FileInputStream is = new FileInputStream("Student.xml");

         // get a new SAXParser
         SAXParser parser = factory.newSAXParser();

         // parse the file
         String systemId = "";
         parser.parse(is, handler, systemId);

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

If we compile the code and execute it, this will produce the following result −


   
12

   
Malik

javax_xml_parsers_saxparser.htm
Advertisements