Read XML(Using XMLConfiguration)

Read XML(Using XMLConfiguration)

需 import 下列 jar:

commons-collections-3.2.jar

commons-configuration-1.6.jar

commons-lang-2.5.jar

commons-logging-1.1.1.jar

程式位置結構如下列:

image

SystemConfig.xml


<SysConfig>
    <AppSettings>
    	<RunMode>DEV</RunMode> <!-- DEV, UAT, PROD-->
    	<SysAdminMail>xxx@abc.com</SysAdminMail>
    </AppSettings>
    
    <DEV_DB>
		<IP>10.12.123.10</IP>
		<Port>8080</Port>
		<UID>dev</UID>
		<Account>admin</Account>
		<Password>1234</Password>
    </DEV_DB>
    
    <UAT_DB>
		<IP>10.12.123.11</IP>
		<Port>8080</Port>
		<UID>uat</UID>
		<Account>admin</Account>
		<Password>1234</Password>
    </UAT_DB>
    
    <PROD_DB>
		<IP>10.12.123.12</IP>
		<Port>8080</Port>
		<UID>prod</UID>
		<Account>admin</Account>
		<Password>1234</Password>
    </PROD_DB>
</SysConfig>

DemoConfiguration.java



import java.net.URL;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;

public class DemoConfiguration extends XMLConfiguration 
{
	private static final long serialVersionUID = 1L;
	private static DemoConfiguration config;
	
    private DemoConfiguration(URL url) throws ConfigurationException
    {
        super(url);
    }
    
	public static DemoConfiguration getInstance() throws ConfigurationException
    {
		//implement singleton
        if(config == null)
        {
        	config = new DemoConfiguration(DemoConfiguration.class.getClassLoader().getResource("config/SystemConfig.xml")); //xml 的 package 名稱不能含有點".", 只能是字串 
        }
        
        return config;
    }
	
    public String getRunMode()
    {
        return config.getString("AppSettings.RunMode");
    }
    
    public String getIP()
    {
    	return config.getString(getRunMode() + "_DB" + ".IP");
    }
    
    public String getPort()
    {
    	return config.getString(getRunMode() + "_DB" + ".Port");
    }
    
    public String getUID()
    {
    	return config.getString(getRunMode() + "_DB" + ".UID");
    }
    
    public String getAccount()
    {
    	return config.getString(getRunMode() + "_DB" + ".Account");
    }
    
    public String getPassword()
    {
    	return config.getString(getRunMode() + "_DB" + ".Password");
    }
}





DemoMain.java



import org.apache.commons.configuration.ConfigurationException;

public class DemoMain 
{
	public static void main(String[] args) 
	{
		DemoConfiguration conf = null;
        try
        {
            conf = DemoConfiguration.getInstance();
            System.out.println("DB account: " + conf.getAccount());
            System.out.println("DB password: " + conf.getPassword());
        }
        catch (ConfigurationException e)
        {
        	System.out.println("error");
        }
	}
}

Console:

DB account: admin
DB password: 1234