1.将要解析的xml文件:
<?xml version="1.0" encoding="UTF-8"?> <HD> <disk name="A"> <capacity>100G</capacity> <directories>250</directories> <files>1500</files> </disk> <disk name="B"> <capacity>200G</capacity> <directories>500</directories> <files>3000</files> </disk> </HD>
2.解析xml的Java代码:
import java.io.IOException;
import java.util.*;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.*;
public class JdomTest {
public static void main(String[] args) throws Exception, IOException{
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(JdomTest.class.getClassLoader().getResourceAsStream("test.xml"));
Element root = doc.getRootElement();//获取根元素
List list = root.getChildren("disk");//获取名为disk的所有元素
for (int i = 0; i < list.size(); i++) {
Element element = (Element) list.get(i);
String name = element.getAttributeValue("name");
String capacity = element.getChildText("capacity");
String directories = element.getChildText("directories");
String files = element.getChildText("files");
System.out.println("磁盘信息:");
System.out.println("分区盘符:" + name);
System.out.println("分区容量:" + capacity);
System.out.println("目录数:" + directories);
System.out.println("文件数:" + files);
System.out.println("------------------------------------");
}
}
}
①<HD>即为java代码中的getRootElement()所获取的根元素
②<disk>即为<HD>的子标签,通过getChildren()获取,该方法返回一个List,每个<disk></disk>最为一个element对象存在该list中。
capacity, directories, files通过getChildText()获得。
说明:xml代码来自网上,解析用例。
附件附上jdom-2.0.5.jar