Java JDOM Document getNamespacesIntroduced() Method



The Java JDOM getNamespacesIntroduced() method of Document class is used to get all the namespaces that are introduced by the current XML document at the document level. This method doesn't retrieve the inherited namespaces, it retrieves only those namespaces that are introduced by the current document.

Syntax

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

Document.getNamespacesIntroduced();

Parameters

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

Return Value

The Java getNamespacesIntroduced() method returns the list of introduced Namespace objects.

Example

Here is the basic example of using the Java JDOM Document getNamespacesIntroduced() method −

import java.util.List;
import org.jdom2.Document;
import org.jdom2.Namespace;

public class NamespacesIntroduced {
   public static void main(String args[]) {
      try {    	  
    	 //Create a new document
    	 Document doc = new Document();
    	 //Get Introduced Namespaces
		 List<Namespace> ns = doc.getNamespacesIntroduced();
		 for(Namespace namespace : ns) {
			System.out.println(namespace);
		 }		 
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The list of introduced namespaces are displayed.

[Namespace: prefix "" is mapped to URI ""]
[Namespace: prefix "xml" is mapped to URI "http://www.w3.org/XML/1998/namespace"]

Example 2

We need to parse the following books.xml file −

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

The Document.getNamespacesIntroduced() method retrieves only the default namespace that is already introduced by any XML document even though the root element and its child elements have namespaces as this method operates only at document level.

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

public class NamespacesIntroduced1 {
   public static void main(String args[]) {
      try {    
         //Reading the XML file
		 SAXBuilder saxBuilder = new SAXBuilder();
		 File inputFile = new File("books.xml");			          
		 Document doc = saxBuilder.build(inputFile);
		 //Get Introduced Namespaces
		 List<Namespace> ns = doc.getNamespacesIntroduced();
		 for(Namespace namespace : ns) {
			System.out.println(namespace);	
		 }
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

The default namespace at document level is displayed.

[Namespace: prefix "" is mapped to URI ""]
[Namespace: prefix "xml" is mapped to URI "http://www.w3.org/XML/1998/namespace"]
Advertisements