Java JDOM Element getContentSize() 方法



Java JDOM 的 getContentSize() 方法是 Element 类的方法,用于获取 XML 元素内内容对象的个数。这些内容对象包括子元素、注释、文本等。此方法也把空格计算在内,作为一个空文本。

语法

以下是 Java JDOM Element getContentSize() 方法的语法:

Element.getContentSize();

参数

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

返回值

Java getContentSize() 方法返回内容对象的个数,以整数形式表示。

示例 1

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

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

public class GetContentSize {
   public static void main(String args[]) {
      try {	
    	 //Create Document and add root
	     Document doc = new Document();
	     Element root = new Element("root").setText("I'm the root");
	     doc.setRootElement(root);
	     //Get content size of root
	     int contentSize = root.getContentSize();
    	 System.out.println("No.of content objects : "+contentSize);	     
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

显示根元素内的内容对象数量。

No.of content objects : 1

示例 2

我们需要解析以下 library.xml 文件:

<library>
	Readers choice 
	<!--Book information is available here -->
   <book>War and peace</book>
</library>

getContentSize() 方法将空格计算为空文本并返回结果。

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

public class GetContentSize {
   public static void main(String args[]) {
      try {
         //Reading the document and get the root
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("library.xml");
    	 Document doc = saxBuilder.build(inputFile);
    	 Element root = doc.getRootElement();
    	 //Get content size
    	 int contentSize = root.getContentSize();
    	 System.out.println("No.of content objects : "+contentSize);	  
      } catch(Exception e) {
    	 e.printStackTrace();
      }
   }
}

输出窗口显示内容对象的个数。

No.of content objects : 5
广告
© . All rights reserved.