Java JDOM Element getNamespacePrefix() Method



The Java JDOM getNamespacePrefix() method of Element class is used to get the prefix associated with an XML Element. If there is no prefix for an element, it returns an empty string.

Syntax

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

Element.getNamespacePrefix();

Parameters

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

Return Value

The Java getNamespacePrefix() method returns the prefix in the form of a string.

Example 1

Here is the sample.xml file that has a prefix for the root element.

<?xml version="1.0" encoding="UTF-8"?>
<Book_Prefix:root xmlns:Book_Prefix="https://namespaces/root1" >I'm root.</Book_Prefix:root>

Using the Java JDOM Element getNamespacePrefix() method, we can get the prefix associated with the element as follows −

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

public class GetNSPrefix {
   public static void main(String args[]) {
      try {	
    	 //Reading the document
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("sample.xml");
    	 Document doc = saxBuilder.build(inputFile);
    	 Element root = doc.getRootElement();
	     //Get namespace prefix
    	 String prefix = root.getNamespacePrefix();
    	 System.out.println("Prefix for root : " + prefix);
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The prefix of the root element is displayed.

Prefix for root : Book_Prefix

Example 2

The getNamespacePrefix() method returns an empty string when a prefix is not associated with an XML Element.

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

public class GetNSPrefix {
   public static void main(String args[]) {
      try {	
    	 //Create Document and add root
	     Document doc = new Document();
	     Element root = new Element("root").setText("I'm root. ");
	     doc.setRootElement(root);
	     //Get namespace prefix
    	 String prefix = root.getNamespacePrefix();
    	 System.out.println("Prefix for root : " + prefix);      
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

An empty string is displayed as a prefix.

Prefix for root :
Advertisements