您的位置:首页 > 其它

利用 Jaxp (Sax) 解析xml文件--- 解析指定节点的值

2009-11-22 11:30 381 查看
package tao.test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SqlServer {
private String username;
private String password;
private String url;
private String driver;
/**
* 存储结果
*/
Map map = new HashMap();

/**
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public SqlServer() throws SAXException, IOException, ParserConfigurationException {

String userDir = System.getProperty("user.dir");
String eosConfig = new File(userDir).getParent()
+ "/eosserver/config/eosconfig.xml";

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
// MyHander 是一个内部类
sp.parse(new File(eosConfig), new MyHandler());

this.username = map.get("username").toString().trim();
this.password = map.get("password").toString().trim();
this.url = map.get("jdbcurl").toString().trim();
this.driver = map.get("jdbcdriver").toString().trim();
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
/**
*
*/
class MyHandler extends DefaultHandler {

List keys = new ArrayList() {
{
add("username");
add("password");
add("jdbcurl");
add("jdbcdriver");
}
};

String key = null;
private int index = 0;
private int flag = index;

public void characters(char ch[], int start, int length)
throws SAXException {
String value = new String(ch, start, length);
if (flag == index - 1) {
map.put(key, value);
flag = index;
}
}

public void startElement(String uri, String localName, String qName,
Attributes attr) throws SAXException {
if ("configValue".equals(qName)) {
if (keys.contains(attr.getValue("key"))) {
key = attr.getValue("key");
index++;
}
}
}

}

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
new SqlServer();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: