Java JDOM Document setBaseURI() Method



The Java JDOM setBaseURI() method of Document class sets the URI, which is the base location from which the XML document is loaded. This method sets the BaseURI for documents that doesn't have any URI or replaces the already existing URI.

Syntax

Following is the syntax of the Java JDOM Document setBaseURI() method −

Document.setBaseURI(baseURI);

Parameters

The Java JDOM Document setBaseURI() method accepts a single parameter.

baseURI − a string value that represents the URI we need to set.

Return Value

The Java baseURI() method has no return value.

Example 1

The following basic example uses the Java JDOM Document setBaseURI() method to set the URI of a newly created XML document.

import org.jdom2.Document;

public class GetBaseURI {
   public static void main(String args[]) {
      try {	
    	 //Creating a new Document 
	     Document doc = new Document();
	     String baseURI = doc.getBaseURI();
	     System.out.println("Base URI before setting : "+baseURI);
	     //set BaseURI
	     doc.setBaseURI("http://tutotialspoint/javaxml/company");
	     baseURI = doc.getBaseURI();
	     System.out.println("Base URI after setting : "+baseURI);
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The BaseURI before and after setting URI is displayed.

Base URI before setting : null
Base URI after setting : http://tutotialspoint/javaxml/company

Example 2

The setBaseURI() method used in the following program updates the already existing relative URI. The lengthy relative URI is now replaced with the shorter one.

import java.io.File;
import org.jdom2.Document;
import org.jdom2.input.SAXBuilder;

public class GetBaseURI {
   public static void main(String args[]) {
      try {	
         //Reading the document
	     SAXBuilder saxBuilder = new SAXBuilder();
	     File inputFile = new File("src/bookstore.xml");
	     Document doc = saxBuilder.build(inputFile);
	     String baseURI = doc.getBaseURI();
		 System.out.println("Base URI before updating : "+baseURI);
		 doc.setBaseURI("http://tutotialspoint/Java_xml");
		 baseURI = doc.getBaseURI();
		 System.out.println("Base URI after updating : "+baseURI);
      } catch (Exception e) {
	      e.printStackTrace();
	  }
   }
}

The old and the updated BaseURI are displayed.

Base URI before updating : file:/C:/Users/Tutorialspoint/eclipse-workspace/Java_xml/src/bookstore.xml
Base URI after updating : http://tutotialspoint/Java_xml
Advertisements