jdom解析xml

    技术2022-05-11  8

     import java.io.FileOutputStream;import java.io.UnsupportedEncodingException;import java.util.List;

    import org.jdom.*;import org.jdom.input.*;import org.jdom.output.XMLOutputter;

    public class Config { private String configPath = new String(); private Document doc;

     public Config() { }

     public String getConfigPath() {  return configPath; }

     /**  * @param configPath  *            获取xml文件的路径  * @return   */ public void setConfigPath(String configPath) {  configPath = new Config().getClass().getClassLoader().getResource(".")+configPath ;  try {   configPath = java.net.URLDecoder.decode(configPath,"utf-8");  } catch (UnsupportedEncodingException ex) {   ex.printStackTrace();  }   configPath = configPath.substring(6, configPath.length()) ;  this.configPath = configPath ; }

     /**  * @param Param ,value  *           向xml文件中插入数据  * @return boolean  */ public boolean set(String Param, String value) {  try {   SAXBuilder builder = new SAXBuilder(false);   doc = builder.build(this.configPath);   Element element = doc.getRootElement();   List list = element.getChildren() ;   if(element.getChild(Param)==null) {    Element pass = new Element(Param) ;    pass.addContent(value) ;    element.addContent(pass) ;   }else {    element.getChild(Param).setText(value);   }//    List booklist=element.getChildren("email"+Param);//    for(int i=0 ;i<booklist.size(); i++) {//     Element book = (Element) booklist.get(i);//     String email=book.getText() ;//     System.out.println("========"+email);//     book.getChild(Param).setText(value);//    }   XMLOutputter outputter = new XMLOutputter();   outputter.output(doc, new FileOutputStream(this.configPath));  } catch (Exception ex) {   ex.printStackTrace();   return false;  }  return true; }

     /**  * @param Param   *           从xml文件中获取参数  * @return String  */ public String get(String Param) {  // TODO: 从配置文件获得相应参数  String value = null ;  try {   SAXBuilder builder = new SAXBuilder(false);   doc = builder.build(this.configPath);   Element element = doc.getRootElement();   value = element.getChildTextTrim(Param) ;  } catch (Exception ex) {   ex.printStackTrace();  }  return value ; }}


    最新回复(0)