DocumentBuilder setEntityResolver() Method



Description

The Javax.xml.parsers.DocumentBuilder.setEntityResolver(EntityResolver er) method specifies the EntityResolver to be used to resolve entities present in the XML document to be parsed. Setting this to null will result in the underlying implementation using it's own default implementation and behavior.

Declaration

Following is the declaration for Javax.xml.parsers.DocumentBuilder.setEntityResolver() method

public abstract void setEntityResolver(EntityResolver er)

Parameters

er − The EntityResolver to be used to resolve entities present in the XML document to be parsed.

Return Value

This method does not return a value.

Exception

NA

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.DocumentBuilder.setEntityResolver() method.

package com.tutorialspoint;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

// an EntityResolver for our builder.
class Resolver implements EntityResolver {

   public InputSource resolveEntity(String publicId, String systemId) {
      if (systemId.equals("")) {
         System.out.println("Resolving Entity...");
         return null;
      } else {
         // use the default behaviour
         return null;
      }
   }
}

public class DocumentBuilderDemo {

   public static void main(String[] args) {

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

      try {
         // use the factory to create a documentbuilder
         DocumentBuilder builder = factory.newDocumentBuilder();

         Resolver res = new Resolver();
         builder.setEntityResolver(res);

         // create a new document from input stream and an empty systemId
         Document doc = builder.parse("Student.xml");

         // get the first element
         Element element = doc.getDocumentElement();

         // get all child nodes
         NodeList nodes = element.getChildNodes();

         // print the text content of each child
         for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println("" + nodes.item(i).getTextContent());
         }

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

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


   
12

   
Malik


javax_xml_parsers_documentbuilder.htm
Advertisements