Java用jdom.jar解析读取XML文件信息
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 + "\n" + "directories:" + directories + "\n" + "files:" + files + "\r----------------------------------------"); } } 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
----------------------------------------
漫人生路上,该放下的要放下,往事如过眼烟云,浅笑则安...