读取xml后缀的配置文件
源代码:
package com.web;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ReadXMLDemo {
public static void main(String[] args) {
try {
SAXReader reader = new SAXReader();
File xmlFile = new File("E:/workspace/webProject/resource/score.xml");
if(!xmlFile.exists())
{
System.out.println("scores.xml is not exists!");
}
Document doc = reader.read(xmlFile);
// 得到根节点:students
Element root = doc.getRootElement();
// 得到students的所有子节点:student
Iterator<Element> it = root.elementIterator();
// 处理每个student
while (it.hasNext()) {
// 得到每个学生
Element stuElem = it.next();
// System.out.println(stuElem);
// 输出学生的属性:id
List<Attribute> attrList = stuElem.attributes();
for (Attribute attr : attrList) {
String name = attr.getName();
String value = attr.getValue();
System.out.println(name + "----->" + value);
}
// 输出学生的子元素:name,course,score
Iterator<Element> it2 = stuElem.elementIterator();
while (it2.hasNext()) {
Element elem = it2.next();
String name = elem.getName();
String text = elem.getText();
System.out.println(name + "----->" + text);
//获取子元素的属性
if(name.equals("course"))
{
List<Attribute> attrCourse = elem.attributes();
for (Attribute attr : attrCourse) {
String name2 = attr.getName();
String value = attr.getValue();
System.out.println(name2 + "----->" + value);
}
}
}
System.out.println();
}
} catch (Exception e) {
}
}
}
此文件需要注意的点:
1、读取的是properties文件,文件后缀不能错误,错误将提示找不到文件
2、配置文件要和类在同一个bin目录下,如果需要分开在buildpath中source中新建文件夹