7.7. Configuring Applications with XML
Problem
You need to configure an application with an XML document.
Solution
Use an implementation of XMLConfiguration
to load
configuration parameters from an XML document. The following XML
document contains configuration information that is loaded with a
DOMConfiguration
object:
<?xml version="1.0" encoding="ISO-8859-1" ?> <engine-config> <start-criteria> <criteria type="critical"> Temperature Above -10 Celsius </criteria> <criteria> Fuel tank is not empty </criteria> </start-criteria> <name> <first>Tom</first> <last>Payne</last> </name> <horsepower>42</horsepower> </engine-config>
A DOMConfiguration
object uses the Xerces XML
parser to parse an entire XML document into a DOM
Document
object. Subsequent calls to methods on
the Configuration
interface cause the
DOMConfiguration
object to traverse nodes in the
Document
. The code to read in this XML
configuration with DOMConfiguration
follows:
import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.DOMConfiguration; String resource = "com/discursive/jccook/configuration/global.xml"; Configuration config = new DOMConfiguration(resource); // Retrieve a list of all Criteria elements List startCriteria = config.getList("start-criteria.criteria"); // Retrieve the value of the first criteria element String firstCriteria = config.getString("start-criteria.criteria(0)"); // Retrieve the type attribute of the first criteria element String firstCriteriaType = config.getString("start-criteria.criteria(0)[@type]"); ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.