1.去官网下载jdom的jar包
http://www.jdom.org/
2.xml
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
<?
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 >
< 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 >
3. java代码
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
package
test;
import java.io.IOException;
import java.util. * ;
import org.jdom. * ;
import org.jdom.input.SAXBuilder;
import java.io.IOException;
import java.util. * ;
import org.jdom. * ;
import org.jdom.input.SAXBuilder;
public class Simple1 {
public static void main(String[] args) throws JDOMException, IOException {
File file = new File("test.xml");//创建文件
InputStream in = new FileInputStream(file);//输入流
SAXBuilder sb
=
new
SAXBuilder();
Document doc = sb.build(in ); // 构造文档对象
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 " ); // 取disk子元素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( " ----------------------------------- " );
}
}
}
Document doc = sb.build(in ); // 构造文档对象
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 " ); // 取disk子元素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( " ----------------------------------- " );
}
}
}