java使用dom4j读取xml的例子
dom4j下载地址:http://sourceforge.net/projects/dom4j/files/dom4j/1.6.1/dom4j-1.6.1.tar.gz/download
例如读取如下xml文件:
8G200158010G5003000dom4j读取上面xml文件的代码如下:
public class Simple {
public static void main(String[] args) throws DocumentException {
SAXReader reader = new SAXReader();
Document doc = reader.read(Simple.class.getClassLoader()
.getResourceAsStream("test.xml")); // 构造文档对象
Element root = doc.getRootElement(); // 获取根元素
Element foo;
for (Iterator i = root.elementIterator("disk"); i.hasNext();) {
foo = (Element) i.next();
System.out.println("磁盘信息:");
System.out.println("分区盘符:" + foo.attributeValue("name"));
System.out.println("分区容量:" + foo.elementText("capacity"));
System.out.println("目录数:" + foo.elementText("directories"));
System.out.println("文件数:" + foo.elementText("files"));
System.out.println("-----------------------------------");
}
}
}