通过JDom读取XML文件

来源:互联网 发布:java的工厂设计模式 编辑:程序博客网 时间:2024/06/07 12:34

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class ReadConfig {
 private static ReadConfig config = new ReadConfig();

 private ReadConfig() {
 }

 public static ReadConfig getInstance() {
  return config;
 }

 public String getPath() {
  
  String path = this.getClass().getResource("").getPath();
  path = path.substring(0, path.indexOf("classes"));
  path += "classes/conf.xml";
  //解决配置文件路径问题,把%20改成空格
  path=path.replaceAll("%20", " ");
  // URL url=ReadConfig.class.getClassLoader().getResource("");
  // String path=url.getPath()+"/conf.xml";
  
  return path;
 }
 public  Map<String, String> readFromXml() {
  Map<String, String> map = new HashMap<String, String>();
  SAXBuilder sb = new SAXBuilder();
  try {
   Document doc = sb.build(new FileInputStream(getPath()));
   Element root = doc.getRootElement();
   List root1 = root.getChildren();
   List sib=null;
   for (Object root2 : root1) {//这里使用增强循环
    sib=((Element)root2).getChildren();
    //System.out.println(sib);
    for(Object elee:sib)
    {
     Element e=(Element)elee;
     map.put(e.getName(), e.getText());
     //System.out.println(e.getName()+"="+e.getText());
    }
   }

  } catch (FileNotFoundException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  } catch (JDOMException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  } catch (IOException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }
  return map;

 }
}
 

原创粉丝点击