请教各位高手怎样用JAVA解析XML,请给些代码
请教各位高手怎样用JAVA解析XML,请给些代码
请教各位高手怎样用JAVA解析XML,请给些代码
答案:我一般用DOM解析实例:import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Iterator;
import java.util.Properties;import org.dom4j.DocumentHelper;
import org.dom4j.Element;import com.briup.util.BackUP;
import com.briup.util.Configuration;
import com.briup.util.Logger;
import com.briup.woss.client.Client;
import com.briup.woss.client.Gather;
import com.briup.woss.server.DBStore;
import com.briup.woss.server.Server;public class ConfigurationImpl {
private static Element root; //根结点
private static Properties properties = new Properties();//携带参数static { //静态初始化
File file = new File("conf/configuration.xml"); // 拿到文件
try {
FileReader fr = new FileReader(file); // 拿到文件解读器
BufferedReader br = new BufferedReader(fr); // 拿到字符过滤流
String result = ""; // 结果集
String tempStr; // 中间字符
while ((tempStr = br.readLine()) != null) // 获取结果
{
result = result + tempStr;
}
root = DocumentHelper.parseText(result).getRootElement();
} catch (Exception e) {
e.printStackTrace();
}}
public Properties getValue(String tagName) throws Exception {
Element element = root.element(tagName); //获取根结点下的指定结点
Iterator it = element.elementIterator(); // 获取目标节点下的所有元素
while (it.hasNext()) { //循环拿到结点下的元素
Element e = (Element) it.next();
properties.put(e.getName(), e.getStringValue());// 将获得的元素放入properties中
}
return properties;
}public Object getObject(String tagName) throws Exception { //获取对象
Object o = null;
Class c = null;
properties=getValue(tagName);
String classString = properties.getProperty("implement");//实现类的方法
c = Class.forName(classString); //
//实例化
o = c.newInstance();
return o;
}public BackUP getBackup() throws Exception { //获得备份对象
BackUP backup = (BackUP) getObject("backup");
backup.setProperties(properties);
return backup;
}public Client getClient() throws Exception { //获取客户端对象
Client client = (Client) getObject("client");
client.setProperties(properties);
return client;
}public DBStore getDBStore() throws Exception { //获取数据入库对象
DBStore dbStore = (DBStore) getObject("dbstore");
dbStore.setProperties(properties);return dbStore;
}public Gather getGather() throws Exception { //获取采集对象
Gather gather = (Gather) getObject("gather");
gather.setProperties(properties);return gather;
}public Logger getLogger() throws Exception { //获取日志对象
Logger logger = (Logger) getObject("logger");
logger.setProperties(properties);return logger;
}
public Server getServer() throws Exception { //获取服务器对象Server server = (Server) getObject("server");
server.setProperties(properties);
return server;
}
/*
public static void main(String[] args) throws Exception{ //测试
new ConfigurationImpl().getLogger();
}*/
}
好像有两种方法我这里有这两个方法的例子 老师前几天发的 要的话 Q我 我发你!