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



Description

The Javax.xml.parsers.DocumentBuilder.parse(String uri) method parses the content of the given URI as an XML document and return a new DOM Document object. An IllegalArgumentException is thrown if the URI is null null.

Declaration

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

public Document parse(String uri)

Parameters

uri − The location of the content to be parsed.

Return Value

This method returns a new DOM Document object.

Exception

  • IOException − If any IO errors occur.

  • SAXException − If any parse errors occur.

  • IllegalArgumentException − When uri is null

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.parse() 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;

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();

         // 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