Java JDOM Element getNamespace() Method



The Java JDOM getNamespace() method of Element class is used to get the namespaces associated with the element. This method can also be used to get the namespaces linked with a particular prefix. This method returns the Namespaces in the form of Namespace objects of JDOM.

Syntax

Following is the syntax of the Java JDOM Element getNamespace() method −

Element.getNamespace();
Element.getNamespace(prefix);

Parameters

The Java getNamespace() method is a polymorphic method and accepts a single parameter.

prefix − represents the prefix of a namespace to retrieve.

Return Value

The Java getNamespace() method returns the Namespace of an Element.

Example 1

The following book.xml file has namespaces and we are going to use the Java JDOM Element getNamespace() method to obtain them.

<?xml version="1.0" encoding="UTF-16" ?>
<book xmlns="http://domain/book">
    <book:name xmlns:book="http://domain/bookName">
       War and Peace
    </book:name> 
    <auth:name xmlns:auth="http://domain/authorName">
		John Martin
    </auth:name>   
</book>

Here is the basic Java program that implements the usage of getNamespace() method −

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

public class GetNamespace {
   public static void main(String args[]) {
      try {	
    	 //Reading the document
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("book.xml");
    	 Document doc = saxBuilder.build(inputFile);
    	 Element root = doc.getRootElement();
	     //Get namespace
    	 Namespace ns = root.getNamespace();
	     System.out.println(ns);       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The namespace of the root element is displayed.

[Namespace: prefix "" is mapped to URI "http://domain/book"]

Example 2

The getNamespace() method can be used to retrieve the namespace associated with a particular prefix by supplying that as an argument.

import java.io.File;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class GetNamespace {
   public static void main(String args[]) {
      try {	
    	 //Reading the document
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("book.xml");
    	 Document doc = saxBuilder.build(inputFile);
    	 Element root = doc.getRootElement();
	     //Get namespace
    	 List<Element> list = root.getChildren();
    	 for(Element e:list) {
    	    System.out.println(e.getNamespace("auth")); 
    	 }   	     
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The output window displays the namespaces associated with the given prefix.

null
[Namespace: prefix "auth" is mapped to URI "http://domain/authorName"]
Advertisements