实例讲解如何读取和处理XM的配置文件

豆豆网   技术应用频道   2008年02月23日  【字号: 收藏本文

内容摘要:Java和XML是黄金组合,网上已经有很多文章介绍,XML作为电子商务中数据交换,已经有其不可替代的作用,但是在平时系统开发中,我们不一定都用到数据交换,是不是无法使用XML了?

  对上面myenv.xml读取的Java程序:

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import java.util.Properties;
//使用DefaultHandler的好处 是 不必陈列出所有方法,
public class ConfigParser extends DefaultHandler {
////定义一个Properties 用来存放 dbhost dbuser dbpassword的值
private Properties props;
private String currentSet;
private String currentName;
private StringBuffer currentValue = new StringBuffer();
//构建器初始化props
public ConfigParser() {
this.props = new Properties();
}
public Properties getProps() {
return this.props;
}
//定义开始解析元素的方法. 这里是将中的名称xxx提取出来.
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
currentValue.delete(0, currentValue.length());
this.currentName =qName;
}
//这里是将之间的值加入到currentValue
public void characters(char[] ch, int start, int length)
throws SAXException {
currentValue.append(ch, start, length);
}
//在遇到结束后,将之前的名称和值一一对应保存在props中
public void endElement(String uri, String localName,
String qName) throws SAXException {
props.put(qName.toLowerCase(), currentValue.toString().trim());
}
}

来源:豆豆网转载    责编:豆豆技术应用

正在加载评论...