Java JDOM Element getName() 方法



Java JDOM getName() 方法用于获取不含任何命名空间前缀的元素局部名称。

语法

以下是 Java JDOM Element getName() 方法的语法 −

Element.getName();

参数

Java getName() 方法不接受任何参数。

返回值

Java getName() 方法以字符串形式返回元素的局部名称。

示例 1

以下是如何使用 Java JDOM Element getName() 方法的基本示例 −

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();
      }
   }
}

显示根元素的局部名称。

Name of the root : college

示例 2

我们需要解析以下 college.xml 文件 −

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

getName() 方法仅返回不含命名空间前缀的元素名称。

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();
      }
   }
}

显示不含前缀的元素名称。

Name of the root : college
广告
© . All rights reserved.