使用该java.util.Properties.loadFromXML()方法可以轻松完成XML属性的读取。就像从包含键=值对的文件中读取属性一样,XML文件还将包含以以下XML格式包装的键和值。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>Application Configuration</comment> <entry key="data.folder">D:\AppData</entry> <entry key="jdbc.url">jdbc:mysql://localhost/mydb</entry> </properties>
package org.nhooo.example.util; import java.io.FileInputStream; import java.util.Properties; public class LoadXmlProperties { public static void main(String[] args) { LoadXmlProperties lxp = new LoadXmlProperties(); try { Properties properties = lxp.readProperties(); //显示所有属性信息 properties.list(System.out); // 读取data.folder和jdbc.url配置的值 String dataFolder = properties.getProperty("data.folder"); System.out.println("data.folder = " + dataFolder); String jdbcUrl = properties.getProperty("jdbc.url"); System.out.println("jdbc.url = " + jdbcUrl); } catch (Exception e) { e.printStackTrace(); } } private Properties readProperties() throws Exception { Properties properties = new Properties(); FileInputStream fis = new FileInputStream("configuration.xml"); properties.loadFromXML(fis); return properties; } }
上面的代码片段的结果:
-- listing properties -- data.folder=D:\AppData jdbc.url=jdbc:mysql://localhost/mydb data.folder = D:\AppData jdbc.url = jdbc:mysql://localhost/mydb