Java JDOM Element getName() Method



The Java JDOM getName() method of Element class is used to get the local name of the element without any namespace prefix.

Syntax

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

Element.getName();

Parameters

The Java getName() method doesn't accept any parameters.

Return Value

The Java getName() method returns the local name of the element in the form of a string.

Example 1

Here is the basic example of using the Java JDOM Element getName() method −

import org.jdom2.Document;
import org.jdom2.Element;

public class GetName {
   public static void main(String args[]) {
      try {	
    	 //Create Document and add root
	     Document doc = new Document();
	     Element root = new Element("college");
	     doc.setRootElement(root);
	     //Get name of the root
	     String name = root.getName();
    	 System.out.println("Name of the root : "+name);	     
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The local name of the root is displayed.

Name of the root : college

Example 2

We need to parse the following college.xml file −

<pre:college xmlns:pre = "https://college/namespace">
   GVR College
</pre:college>

The getName() method returns only the name of the element without namespace prefix.

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

public class Example2 {
   public static void main(String args[]) {
      try {
         //Reading the document and get the root
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("college.xml");
    	 Document doc = saxBuilder.build(inputFile);
    	 Element root = doc.getRootElement();
	     //Get name of the root
	     String name = root.getName();
    	 System.out.println("Name of the root : "+name);	  
      } catch(Exception e) {
    	 e.printStackTrace();
      }
   }
}

The name of the element without prefix is displayed.

Name of the root : college
Advertisements