码迷,mamicode.com
首页 > 其他好文 > 详细

如何解析xml文件

时间:2015-12-01 14:35:08      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

一.概述-如何解析xml文件

由于项目的环境信息需要经常变动,需要将这些信息配置成全局变量,可以利用一个xml文件来保存这些全局的信息,然后解析这个xml文件,将信息传给到功能api,那么如何解析这个xml文档呢,请看下文,TKS!

二.编写解析xml的工具类ParseXml


public class ParseXml {

private Log log = new Log(this.getClass());

/**
* 解析xml文件,我们需要知道xml文件的路径,然后根据其路径加载xml文件后,生成一个Document的对象,
* 于是我们先定义两个变量String filePath,Document document
* 然后再定义一个load方法,这个方法用来加载xml文件,从而产生document对象。
*/
private String filePath;


private Document document;

/**
* 构造器用来new ParseXml对象时,传一个filePath的参数进来,从而初始化filePath的值
* 调用load方法,从而在ParseXml对象产生时,就会产生一个document的对象。
*/
public ParseXml(String filePath) {
this.filePath = filePath;
this.load(this.filePath);
}

/**
* 用来加载xml文件,并且产生一个document的对象
*/
private void load(String filePath){
File file = new File(filePath);
if (file.exists()) {
SAXReader saxReader = new SAXReader();
try {
document = saxReader.read(file);
} catch (DocumentException e) {
log.info("文件加载异常:" + filePath);
throw new DefinedException("文件加载异常:" + filePath);
}
} else{
log.info("文件不存在 : " + filePath);
throw new DefinedException("文件不存在 : " + filePath);
}
}

 

 

三.写一个类来加载这个全局配置的xml文件,转化为静态的数据供功能API直接获取

public class Config {
    
    private static Log log=new Log(Config.class);
    
    public static String browser;
    
    public static int waitTime;
    
    static{
        ParseXml px=new ParseXml("config/config.xml");
        browser=px.getElementText("/config/browser");
        log.info("the browser is: "+ browser);
        waitTime=Integer.valueOf(px.getElementText("/config/waitTime"));
        log.info("the wait time is: "+ waitTime);
    }

}

 

}

如何解析xml文件

标签:

原文地址:http://www.cnblogs.com/liwu/p/5009928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!