利用dom4j解析xml文件

工程中需要对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)
+ "毫秒!");
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值