阅读更多
工程中需要对xml文件进行解析,所以就使用dom4j对xml文件进行解析 不错 蛮好用的!
import java.io.File;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4jDemo {
/**
* the method readXML
*/
public static String time;
public void readXML(String fileName) {
try {
File file = new File(fileName);// 创建文件对象
SAXReader reader = new SAXReader();// 创建SAX阅读器
Document doc = reader.read(file);// 读取内容生成Document对象
Element root = doc.getRootElement();// 取得根节点
search(root);// 开始遍历
} catch (Exception e) {
e.printStackTrace();
}
}
// 递归遍历
private void search(Element root) {
Attribute at = root.attribute("totaltime");
String value = null;
int hours = 0;
int minutes = 0;
int seconds = 0;
if (at != null) {
value = at.getValue();
int date = Integer.parseInt(value);
hours = (date/3600);
minutes = date%3600/60;
seconds = date%3600%60;
}
time = hours+"小时"+minutes+"分"+seconds+"秒";
System.out.println(time);
Iterator it_element = root.elementIterator();// 将根节点下包含的元素组织成一个迭代器
// 迭代
while (it_element.hasNext()) {
Element element = (Element) it_element.next();
if (!element.getText().equals("")) {
System.out.println(element.getName() + "节点的值是"
+ element.getText());
} else {
System.out.println(element.getName() + "节点");
}
Iterator it_attr = element.attributeIterator();
while (it_attr.hasNext()) {
Attribute attr = (Attribute) it_attr.next();
if (attr != null) {
System.out.println(element.getName() + "节点的属性"
+ attr.getName() + "的值是" + attr.getValue());
}
}
search(element);// 递归调用
}
}
/**
* the method main
*/
public static void main(String[] args) {
long start = System.currentTimeMillis();// 开始计时
Dom4jDemo dom4jDemo = new Dom4jDemo();
String fileName = "info.xml";
System.out.println("正在读取文件" + fileName + " ...");
System.out.println("------------------------------------------------");
dom4jDemo.readXML(fileName);
System.out.println("------------------------------------------------");
System.out.println(fileName + "读取成功!");
System.out.println("一共耗时:" + (System.currentTimeMillis() - start)
+ "毫秒!");
}
}