public class XMLConfiguration extends BaseHierarchicalConfiguration implements FileBasedConfiguration, FileLocatorAware, InputStreamSupport
A specialized hierarchical configuration class that is able to parse XML documents.
The parsed document will be stored keeping its structure. The class also tries to preserve as much information from
the loaded XML document as possible, including comments and processing instructions. These will be contained in
documents created by the save() methods, too.
Like other file based configuration classes this class maintains the name and path to the loaded configuration file.
These properties can be altered using several setter methods, but they are not modified by save() and
load() methods. If XML documents contain relative paths to other documents (e.g. to a DTD), these references
are resolved based on the path set for this configuration.
By inheriting from AbstractConfiguration this class provides some extended functionality, e.g. interpolation
of property values. Like in PropertiesConfiguration property values can contain delimiter characters (the
comma ',' per default) and are then split into multiple values. This works for XML attributes and text content of
elements as well. The delimiter can be escaped by a backslash. As an example consider the following XML fragment:
<config> <array>10,20,30,40</array> <scalar>3\,1415</scalar> <cite text="To be or not to be\, this is the question!"/> </config>
Here the content of the array element will be split at the commas, so the array key will be assigned
4 values. In the scalar property and the text attribute of the cite element the comma is
escaped, so that no splitting is performed.
The configuration API allows setting multiple values for a single attribute, e.g. something like the following is legal (assuming that the default expression engine is used):
XMLConfiguration config = new XMLConfiguration();
config.addProperty("test.dir[@name]", "C:\\Temp\\");
config.addProperty("test.dir[@name]", "D:\\Data\\");
However, in XML such a constellation is not supported; an attribute can appear only once for a single element. Therefore, an attempt to save a configuration which violates this condition will throw an exception.
Like other Configuration implementations, XMLConfiguration uses a ListDelimiterHandler object
for controlling list split operations. Per default, a list delimiter handler object is set which disables this
feature. XML has a built-in support for complex structures including list properties; therefore, list splitting is
not that relevant for this configuration type. Nevertheless, by setting an alternative ListDelimiterHandler
implementation, this feature can be enabled. It works as for any other concrete Configuration implementation.
Whitespace in the content of XML documents is trimmed per default. In most cases this is desired. However, sometimes whitespace is indeed important and should be treated as part of the value of a property as in the following example:
<indent> </indent>
Per default the spaces in the indent element will be trimmed resulting in an empty element. To tell
XMLConfiguration that spaces are relevant the xml:space attribute can be used, which is defined in
the XML specification. This will look as follows:
<indent xml:space="preserve"> </indent>
The value of the indent property will now contain the spaces.
XMLConfiguration implements the FileBasedConfiguration interface and thus can be used together with a
file-based builder to load XML configuration files from various sources like files, URLs, or streams.
Like other Configuration implementations, this class uses a Synchronizer object to control concurrent
access. By choosing a suitable implementation of the Synchronizer interface, an instance can be made
thread-safe or not. Note that access to most of the properties typically set through a builder is not protected by
the Synchronizer. The intended usage is that these properties are set once at construction time through the
builder and after that remain constant. If you wish to change such properties during life time of an instance, you
have to use the lock() and unlock() methods manually to ensure that other threads see your changes.
More information about the basic functionality supported by XMLConfiguration can be found at the user's guide
at Basic
features and AbstractConfiguration. There is also a separate chapter dealing with
XML Configurations in
special.
BaseHierarchicalConfiguration.BuilderVisitor| Constructor and Description |
|---|
XMLConfiguration()
Creates a new instance of
XMLConfiguration. |
XMLConfiguration(HierarchicalConfiguration<ImmutableNode> c)
Creates a new instance of
XMLConfiguration and copies the content of the passed in configuration into this
object. |
| Modifier and Type | Method and Description |
|---|---|
protected DocumentBuilder |
createDocumentBuilder()
Creates the
DocumentBuilder to be used for loading files. |
protected Transformer |
createTransformer()
Creates and initializes the transformer used for save operations.
|
Document |
getDocument()
Returns the XML document this configuration was loaded from.
|
DocumentBuilder |
getDocumentBuilder()
Returns the
DocumentBuilder object that is used for loading documents. |
EntityResolver |
getEntityResolver()
Returns the EntityResolver.
|
String |
getPublicID()
Returns the public ID of the DOCTYPE declaration from the loaded XML document.
|
protected String |
getRootElementNameInternal()
Returns the name of the root element.
|
String |
getSystemID()
Returns the system ID of the DOCTYPE declaration from the loaded XML document.
|
void |
initFileLocator(FileLocator loc)
Passes the current
FileLocator to this object. |
boolean |
isSchemaValidation()
Returns the value of the schemaValidation flag.
|
boolean |
isValidating()
Returns the value of the validating flag.
|
void |
read(InputStream in)
Loads the configuration from the given input stream.
|
void |
read(Reader in)
Loads the configuration from the given reader.
|
void |
setDocumentBuilder(DocumentBuilder documentBuilder)
Sets the
DocumentBuilder object to be used for loading documents. |
void |
setEntityResolver(EntityResolver resolver)
Sets a new EntityResolver.
|
void |
setPublicID(String publicID)
Sets the public ID of the DOCTYPE declaration.
|
void |
setRootElementName(String name)
Sets the name of the root element.
|
void |
setSchemaValidation(boolean schemaValidation)
Sets the value of the schemaValidation flag.
|
void |
setSystemID(String systemID)
Sets the system ID of the DOCTYPE declaration.
|
void |
setValidating(boolean validating)
Sets the value of the validating flag.
|
void |
validate()
Validate the document against the Schema.
|
void |
write(Writer writer)
Saves the configuration to the specified writer.
|
void |
write(Writer writer,
Transformer transformer)
Saves the configuration to the specified writer.
|
childConfigurationsAt, childConfigurationsAt, cloneNodeModel, configurationAt, configurationAt, configurationsAt, configurationsAt, createSubConfigurationForTrackedNode, getNodeModel, getSubConfigurationNodeSelector, getSubConfigurationParentModel, immutableChildConfigurationsAt, immutableConfigurationAt, immutableConfigurationAt, immutableConfigurationsAt, initSubConfigurationForThisParent, interpolatedConfiguration, subnodeConfigurationChanged, subsetaddNodes, addNodesInternal, addPropertyDirect, addPropertyInternal, clearInternal, clearPropertyDirect, clearTree, clearTreeInternal, clone, containsKeyInternal, fetchNodeList, getExpressionEngine, getKeysInternal, getKeysInternal, getMaxIndex, getMaxIndexInternal, getModel, getPropertyInternal, getRootElementName, isEmptyInternal, nodeDefined, nodeKey, resolveAddKey, resolveKey, resolveNodeKey, resolveUpdateKey, setExpressionEngine, setPropertyInternal, sizeInternal, toStringaddErrorLogListener, addProperty, append, beginRead, beginWrite, clear, clearProperty, cloneInterpolator, containsKey, copy, endRead, endWrite, get, get, getArray, getArray, getBigDecimal, getBigDecimal, getBigInteger, getBigInteger, getBoolean, getBoolean, getBoolean, getByte, getByte, getByte, getCollection, getCollection, getConfigurationDecoder, getConversionHandler, getDouble, getDouble, getDouble, getDuration, getDuration, getEncodedString, getEncodedString, getFloat, getFloat, getFloat, getInt, getInt, getInteger, getInterpolator, getKeys, getKeys, getList, getList, getList, getList, getListDelimiterHandler, getLogger, getLong, getLong, getLong, getProperties, getProperties, getProperty, getShort, getShort, getShort, getString, getString, getStringArray, getSynchronizer, immutableSubset, initLogger, installInterpolator, interpolate, interpolate, isEmpty, isScalarValue, isThrowExceptionOnMissing, lock, setConfigurationDecoder, setConversionHandler, setDefaultLookups, setInterpolator, setListDelimiterHandler, setLogger, setParentInterpolator, setPrefixLookups, setProperty, setSynchronizer, setThrowExceptionOnMissing, size, unlockaddEventListener, clearErrorListeners, clearEventListeners, copyEventListeners, createErrorEvent, createEvent, fireError, fireEvent, getEventListenerRegistrations, getEventListeners, isDetailEvents, removeEventListener, setDetailEventsequals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitaddProperty, clear, clearProperty, getInterpolator, installInterpolator, setInterpolator, setProperty, subsetcontainsKey, get, get, getArray, getArray, getBigDecimal, getBigDecimal, getBigInteger, getBigInteger, getBoolean, getBoolean, getBoolean, getByte, getByte, getByte, getCollection, getCollection, getDouble, getDouble, getDouble, getDuration, getDuration, getEncodedString, getEncodedString, getEnum, getEnum, getFloat, getFloat, getFloat, getInt, getInt, getInteger, getKeys, getKeys, getList, getList, getList, getList, getLong, getLong, getLong, getProperties, getProperty, getShort, getShort, getShort, getString, getString, getStringArray, immutableSubset, isEmpty, sizegetSynchronizer, lock, setSynchronizer, unlockpublic XMLConfiguration()
XMLConfiguration.public XMLConfiguration(HierarchicalConfiguration<ImmutableNode> c)
XMLConfiguration and copies the content of the passed in configuration into this
object. Note that only the data of the passed in configuration will be copied. If, for instance, the other
configuration is a XMLConfiguration, too, things like comments or processing instructions will be lost.c - the configuration to copyprotected String getRootElementNameInternal()
getRootElementNameInternal in class AbstractHierarchicalConfiguration<ImmutableNode>public void setRootElementName(String name)
UnsupportedOperationException
exception is thrown. Whether this configuration has been loaded from an XML document or not can be found out using
the getDocument() method.name - the name of the root elementpublic DocumentBuilder getDocumentBuilder()
DocumentBuilder object that is used for loading documents. If no specific builder has been set,
this method returns null.DocumentBuilder for loading new documentspublic void setDocumentBuilder(DocumentBuilder documentBuilder)
DocumentBuilder object to be used for loading documents. This method makes it possible to specify
the exact document builder. So an application can create a builder, configure it for its special needs, and then pass
it to this method.documentBuilder - the document builder to be used; if undefined, a default builder will be usedpublic String getPublicID()
public void setPublicID(String publicID)
publicID - the public IDpublic String getSystemID()
public void setSystemID(String systemID)
systemID - the system IDpublic boolean isValidating()
public void setValidating(boolean validating)
DocumentBuilder was set.validating - the validating flagpublic boolean isSchemaValidation()
public void setSchemaValidation(boolean schemaValidation)
DocumentBuilder was set. If set to true the XML document must
contain a schemaLocation definition that provides resolvable hints to the required schemas.schemaValidation - the validating flagpublic void setEntityResolver(EntityResolver resolver)
resolver - The EntityResolver to use.public EntityResolver getEntityResolver()
public Document getDocument()
protected DocumentBuilder createDocumentBuilder() throws ParserConfigurationException
DocumentBuilder to be used for loading files. This implementation checks whether a specific
DocumentBuilder has been set. If this is the case, this one is used. Otherwise a default builder is created.
Depending on the value of the validating flag this builder will be a validating or a non validating
DocumentBuilder.DocumentBuilder for loading configuration filesParserConfigurationException - if an error occursprotected Transformer createTransformer() throws ConfigurationException
ConfigurationException - if an error occurspublic void initFileLocator(FileLocator loc)
FileLocator to this object. Note that this FileLocator object is only temporarily
valid for the following invocation of read() or write(. Depending on the state of the
FileHandler and which of its methods was called, the object may not be fully initialized. For instance, if
the FileHandler's load(InputStream) method was called, no file information is available, and all
methods of the FileLocator will return null. Stores the passed in locator for the upcoming IO operation.initFileLocator in interface FileLocatorAwareloc - the current FileLocatorpublic void read(Reader in) throws ConfigurationException, IOException
clear() method is not called, so the properties
contained in the loaded file will be added to the current set of properties.read in interface FileBasedin - the readerConfigurationException - if an error occursIOException - if an IO error occurspublic void read(InputStream in) throws ConfigurationException, IOException
read(Reader), but data is read
from a stream. Note that this method will be called most time when reading an XML configuration source. By reading
XML documents directly from an input stream, the file's encoding can be correctly dealt with.read in interface InputStreamSupportin - the input streamConfigurationException - if an error occursIOException - if an IO error occurspublic void write(Writer writer) throws ConfigurationException, IOException
write in interface FileBasedwriter - the writer used to save the configurationConfigurationException - if an error occursIOException - if an IO error occurspublic void write(Writer writer, Transformer transformer) throws ConfigurationException
writer - the writer used to save the configuration.transformer - How to transform this configuration.ConfigurationException - if an error occurs.public void validate() throws ConfigurationException
ConfigurationException - if the validation fails.Copyright © 2001–2022 The Apache Software Foundation. All rights reserved.