Java JDOM文件的getRootElement()方法



Java JDOM Document 的getRootElement()方法用於從Document類中檢索XML文件的根元素。

語法

以下是Java JDOM Document getRootElement()方法的語法:

Document.getRootElement();

引數

Java getRootElement()方法不接受任何引數。

返回值

Java getRootElement()方法返回一個Element物件,表示根元素。

示例1

這是一個基本的示例,解釋了Java JDOM Document getRootElement()方法的使用:

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

public class GetRootElement {
   public static void main(String args[]) {
      try {	
    	 //Creating a new Document and adding the root
	     Document doc = new Document();
	     Element element = new Element("company");
	     doc.addContent(element);
	     //Getting the root
	     Element root = doc.getRootElement();
	     System.out.println(root);
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

輸出視窗顯示根元素的名稱。

[Element: <company/>]

示例2

當嘗試獲取沒有根元素的文件的根元素時,getRootElement()方法會丟擲IllegalStateException異常。

以下示例說明了這種情況:

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

public class GetRootElement {
   public static void main(String args[]) {
      try {	
    	 //Creating a new Document
	     Document doc = new Document();
	     //Getting the root
	     Element root = doc.getRootElement();
	     System.out.println(root);
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

以上程式丟擲以下異常:

java.lang.IllegalStateException: Root element not set
	at org.jdom2.Document.getRootElement(Document.java:220)
	at getRootElement.Example2.main(Example2.java:12)

示例3

getRootElement()方法只從文件中檢索根元素。它不會像detachRootElement()方法那樣刪除根元素。

我們要從中獲取根元素的bookstore.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Information of a Bookstore (last updated 05-08-2024) -->
<bookstore>
	<book>Treasure Island</book>
	<book>War and Peace</book>
</bookstore>

下面的程式使用getRootElement()方法檢索根元素,並列印文件以檢視根元素是否保留在文件中。

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

public class GetRootElement {
   public static void main(String args[]) {
      try {	
    	 //Reading the document
 		 SAXBuilder saxBuilder = new SAXBuilder();
 		 File inputFile = new File("bookstore.xml");
 		 Document doc = saxBuilder.build(inputFile);		 
 		 //Getting the root
	     Element root = doc.getRootElement();
	     System.out.println(root);
	     //Printing the document
	     XMLOutputter xmlOutput = new XMLOutputter();
	     xmlOutput.setFormat(Format.getPrettyFormat());
	     System.out.println("\n--------XML document after getting the root--------\n");
         xmlOutput.output(doc, System.out);
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

輸出視窗顯示根元素以及使用該方法後的整個文件。

[Element: <bookstore/>]

--------XML document after getting the root--------

<?xml version="1.0" encoding="UTF-8"?>
<!-- Information of a Bookstore (last updated 05-08-2024) -->
<bookstore>
  <book>Treasure Island</book>
  <book>War and Peace</book>
</bookstore>
廣告