Here is how you could compile the XML:
<?xml version="1.0" encoding="UTF-8"?> <config> <jdbc> <url>jdbc:mysql://localhost:3306/javabase</url> <driver>com.mysql.jdbc.Driver</driver> <username>java</username> <password>d$7hF_r!9Y</password> </jdbc> </config>
Assuming it is called config.xml and placed at the root of the classpath, here is an example of how you could load it using JAXP and Xpath :
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.xml"); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(input)); XPath xpath = XPathFactory.newInstance().newXPath(); String url = (String) xpath.compile("//config//jdbc//url").evaluate(document, XPathConstants.STRING); String driver = (String) xpath.compile("//config//jdbc//driver").evaluate(document, XPathConstants.STRING); String username = (String) xpath.compile("//config//jdbc//username").evaluate(document, XPathConstants.STRING); String password = (String) xpath.compile("//config//jdbc//password").evaluate(document, XPathConstants.STRING);
This is just a pretty verbose one, not a properties file. Here is an example of such a properties file:
jdbc.url = jdbc: mysql: // localhost: 3306 / javabase
jdbc.driver = com.mysql.jdbc.Driver
jdbc.username = java
jdbc.password = d $ 7hF_r! 9Y
Assuming it is called config.properties and placed at the root of the class path (or its root path has been added to the class path), here you can load it from the class path:
Properties properties = new Properties(); properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties")); String url = properties.getProperty("jdbc.url"); String driver = properties.getProperty("jdbc.driver"); String username = properties.getProperty("jdbc.username"); String password = properties.getProperty("jdbc.password");
source share