Java JDOM Element indexOf() 方法



Java JDOM 的 indexOf() 方法 (Element 類的方法) 用於獲取 XML 元素內部子內容的索引。內容物件可以是元素、註釋等。子內容物件的索引從 0 開始。如果元素內部不存在這樣的內容物件,則此方法返回 -1。

語法

以下是 Java JDOM Element indexOf() 方法的語法:

Element.indexOf(child);

引數

Java indexOf() 方法接受一個引數。

child − 表示需要查詢其索引的內容物件。

返回值

Java indexOf() 方法返回一個整數值,表示子內容的索引。

示例 1

以下是使用 Java JDOM Element indexOf() 方法的基本示例:

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

public class IndexOfChild {
   public static void main(String args[]) {
      try {	
    	 //Create Document and add elements
	     Document doc = new Document();
	     Element root = new Element("root");
	     doc.setRootElement(root);
	     Element child = new Element("child");
	     root.addContent(child);
	     //Get the index of child
	     int index = root.indexOf(child);
	     System.out.println("Index of child : " + index);       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

顯示子元素的索引。

Index of child : 0

示例 2

如果 XML 元素範圍內不存在這樣的子內容,則 indexOf() 方法返回 -1。

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

public class IndexOfChild {
   public static void main(String args[]) {
      try {	
    	 //Create Document and add elements
	     Document doc = new Document();
	     Element root = new Element("root");
	     doc.setRootElement(root);
	     Element child = new Element("child");
	     //Get the index of child
	     int index = root.indexOf(child);
	     System.out.println("Index of child : " + index);       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

元素的索引顯示為 -1。

Index of child : -1

示例 3

以下是我們需要解析的 sample.xml 檔案:

<root>
	<child1>First child</child1>
	<child2>Second child</child2>
	<child3>Third child</child3>
</root>

indexOf() 方法透過將空格計算為每個元素末尾後的內容物件來返回索引。

import java.io.File;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class IndexOfChild {
   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();
    	 List<Element> list = root.getChildren();	     
	     //Get indices of children
    	 for(int i=1;i<=list.size();i++) {
    	    int index = root.indexOf(list.get(i-1));
    	    System.out.println("Index of child"+i+" : "+ index);	 
    	 }       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

顯示子元素的索引。

Index of child1 : 1
Index of child2 : 3
Index of child3 : 5
廣告