使用XMLConfiguration读取XML文件
包含XMLConfiguration的TestDataReader,用来读取XML文件,并能直接或者字符串,整形数据.要读取的XML文件格式如下:
TestDataReader代码如下:import java.util.Properties;import org.apache.commons.configuration.ConfigurationException;import org.apache.commons.configuration.XMLConfiguration;import org.apache.log4j.Logger;/** * This class is used to parse an xml configuration file and return specified * value. */public final class TestDataReader { private static final String KEY_CONNECTOR = "."; private static final String DATA_FILE_NAME = System .getProperty("user.dir") + "/src/test/resources/testData.xml"; private static final Logger LOGGER = Logger .getLogger(TestDataReader.class); private static TestDataReader instance; private XMLConfiguration xmlConfig; private TestDataReader() { try { xmlConfig = new XMLConfiguration(DATA_FILE_NAME); } catch (ConfigurationException e) { LOGGER.error(e); throw new RuntimeException(e); } } /** * Read String type property. * * @param moduleName related module (second level node in xml). * @param propName property name in xml file (third level node in xml ). * @return property of String type */ public String getStringProperty(String moduleName, String propName) { return xmlConfig.getString(moduleName + KEY_CONNECTOR + propName); } /** * Read int type property. * * @param moduleName related module (second level node in xml). * @param propName property name in xml file (third level node in xml ). * @return property of int type */ public int getIntProperty(String moduleName, String propName) { return xmlConfig.getInt(moduleName + KEY_CONNECTOR + propName); } /** * Read property from hash table. * * @param moduleName related module (second level node in xml). * @param propName property name in xml file (third level node in xml ). * @param eleName key value of the hash table. * @return property of int type */ public String getHashProperty(String moduleName, String propName, String eleName) { // property contains a list key/value pairs Properties property = xmlConfig.getProperties(moduleName + KEY_CONNECTOR + propName); // Look up the list and get the specified value return property.get(eleName).toString(); } /** * Generate identical instance. * * @return identical instance of TestDataReader * @throws ConfigurationException ConfigurationException when instantiating * TestDataReader. */ public static TestDataReader getInstance() { if (instance == null) { instance = new TestDataReader(); } return instance; }}