jdom.jar下载地址1:http://www.jdom.org/downloads/
下载地址2:http://www.java2s.com/Code/Jar/j/Downloadjdomjar.htm
test.xml
<?xml version="1.0" encoding="UTF-8"?> <HD> <disk name="C"> <capacity>8G</capacity> <directories>200</directories> <files>1580</files> </disk> <disk name="D"> <capacity>10G</capacity> <directories>500</directories> <files>3000</files> </disk> </HD>
TestXml.java
import java.io.IOException; import java.util.*; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; public class TestXml { public TestXml() throws JDOMException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(TestXml.class.getClassLoader() .getResourceAsStream("test.xml")); // 构造文档对象 Element root = doc.getRootElement(); // 获取根元素HD List list = root.getChildren("disk"); for (int i = 0; i < list.size(); i++) { Element element = (Element) list.get(i); String capacity = element.getChildText("capacity"); String directories = element.getChildText("directories"); String files = element.getChildText("files"); System.out.println(element.getAttributeValue("name") + ":"); System.out.println("capacity:" + capacity + " " + "directories:" + directories + " " + "files:" + files + " ----------------------------------------"); } } public static void main(String arg[]) { try { TestXml s = new TestXml(); } catch (Exception e) { } } }
测试结果:
C:
capacity:8G
directories:200
files:1580
----------------------------------------
D:
capacity:10G
directories:500
files:3000
----------------------------------------