Java JDOM Element getAttributes() 方法



Java JDOM 的 getAttributes() 方法是 Element 类的,它将 XML 元素的所有属性作为 Attribute 对象列表检索。如果没有任何属性,则此方法将返回一个空列表。

Java JDOM Element 的 getAttributes() 方法返回一个动态列表,因此对这些属性对象所做的任何更改都会影响原始属性。因此,建议使用 hasAttributes() 或 getAttributesSize() 来了解有关元素属性的基本信息。

语法

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

Element.getAttributes();

参数

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

返回值

Java getAttributes() 方法返回 XML 元素的 Attribute 对象列表。

示例 1

这是一个包含两个属性的 department.xml 文件。

<?xml version="1.0" encoding="UTF-8"?>
   <department id="101" code="CS">
      <name>Computer Science</name>
      <staffCount>20</staffCount>
   </department>

以下 Java 程序使用 Java JDOM Element 的 getAttributes() 方法从 department 元素获取属性列表。

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

public class GetAttributes {
   public static void main(String args[]) {
      try {	
    	 //Read the document and get the root
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("department.xml");
    	 Document doc = saxBuilder.build(inputFile);
	     Element root = doc.getRootElement();
	     //Get attributes
	     List<Attribute> attrList = root.getAttributes();
	     System.out.println(attrList);       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

属性列表将显示在输出屏幕上。

[[Attribute: id="101"], [Attribute: code="CS"]]

示例 2

如果 XML 元素没有任何属性,则 getAttributes() 方法将返回一个空列表。

import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;

public class GetAttributes {
   public static void main(String args[]) {
      try {	
    	 //Create Document and set root
	     Document doc = new Document();
	     Element root = new Element("root");
	     doc.setRootElement(root);
	     //Get attributes
	     List<Attribute> attrList = root.getAttributes();
	     System.out.println(attrList);	          
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

输出屏幕上将显示一个空列表。

[]
广告

© . All rights reserved.