DocumentBuilderFactory newInstance() Method



Description

The Javax.xml.parsers.DocumentBuilderFactory.newInstance(String factoryClassName, ClassLoader classLoader) method obtains a new instance of a DocumentBuilderFactory from class name. This function is useful when there are multiple providers in the classpath. It gives more control to the application as it can specify which provider should be loaded.

Once an application has obtained a reference to a DocumentBuilderFactory it can use the factory to configure and obtain parser instances.

Declaration

Following is the declaration for Javax.xml.parsers.DocumentBuilderFactory.newInstance() method

public static DocumentBuilderFactory newInstance(String factoryClassName, 
   ClassLoader classLoader)

Parameters

  • factoryClassName − fully qualified factory class name that provides implementation of javax.xml.parsers.DocumentBuilderFactory.

  • classLoader − ClassLoader used to load the factory class. If null current Thread's context classLoader is used to load the factory class.

Return Value

This method returns a new instance of a DocumentBuilderFactory

Exception

FactoryConfigurationError − if factoryClassName is null, or the factory class cannot be loaded, instantiated.

Example

The following example shows the usage of Javax.xml.parsers.DocumentBuilderFactory.newInstance() method.

package com.tutorialspoint;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class DocumentBuilderFactoryDemo {

   public static void main(String[] args) {

      // set the provider for DocumentBuilder
      String provider =
         "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl";

      // create a new DocumentBuilderFactory from an implementation
      DocumentBuilderFactory factory =
         DocumentBuilderFactory.newInstance(provider, null);

      try {
         // create a new DocumentBuilder
         DocumentBuilder builder = factory.newDocumentBuilder();

         // check the configuration for namespace aware
         System.out.println("" + builder.isNamespaceAware());

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

   }
}

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

false
javax_xml_parsers_documentbuilderfactory.htm
Advertisements