要解析的xml 代码
- xml version="1.0" encoding="GBK"?>
- <sys_para>
- <para>
- <item code="hostname" value="192.168.2.18" description="LDAP服务器IP"/>
- <item code="port" value="389" description="服务器端口"/>
- <item code="admin" value="培训a" description="管理员帐号"/>
- <item code="pwd" value="password" description="密码"/>
- <item code="basedn" value="eweb" description="组织名(基准DN)"/>
- <item code="adminuser" value="admin" description="系统管理员用户"/>
- <item code="adminpwd" value="200200" description="系统管理员密码"/>
- <item code="defaultgroupid" value="47" description="默认组id(无任何权限)"/>
- para>
- sys_para>
java 代码
- package ldap;
- import java.io.*;
- import java.util.*;
- import org.jdom.*;
- import org.jdom.input.SAXBuilder;
- public class UMParas
- {
- private static HashMap prop;
- private static long lastLoadTime;
- private static long interval = 0x186a0L; //refresh per 100 second
- // static Class class$0; /* synthetic field */
- public UMParas()
- {
- }
- //input an para and return the result
- public static synchronized String getPara(String paras)
- throws IllegalArgumentException
- {
- if(paras == null || paras.trim().length() == 0)
- throw new IllegalArgumentException("Parameter's value invalid.");
- long currentTime = System.currentTimeMillis();
- if(prop == null || currentTime - lastLoadTime > interval)
- reloadDom();
- Object obj = prop.get(paras);
- if(obj != null)
- return (String)obj;
- else
- return null;
- }
- //load the xml file
- private static synchronized void reloadDom()
- {
- if(prop == null)
- prop = new HashMap();
- SAXBuilder builder = new SAXBuilder();
- Document read_doc = null;
- try
- {
- read_doc = builder.build(UMParas.class.getResource("ldapconfig.xml"));
- }
- catch(FileNotFoundException e)
- {
- e.printStackTrace();
- }
- catch(JDOMException e)
- {
- e.printStackTrace();
- }
- catch(IOException e)
- {
- e.printStackTrace();
- }
- Element rootElement = read_doc.getRootElement();
- List list = rootElement.getChildren("para");
- for(Iterator i = list.iterator(); i.hasNext();)
- {
- Element current = (Element)i.next();
- List item = current.getChildren("item");
- Attribute code;
- Attribute value;
- for(Iterator j = item.iterator(); j.hasNext(); prop.put(code.getValue(), value.getValue()))
- {
- Element init = (Element)j.next();
- code = init.getAttribute("code");
- value = init.getAttribute("value");
- }
- }
- System.out.println("解析ldapconfig.xml成功");
- lastLoadTime = System.currentTimeMillis();
- }
- public static void main(String args[])
- {
- System.out.println(getPara("hostname"));
- }
- }