gpt4 book ai didi

org.apache.commons.configuration2.XMLConfiguration类的使用及代码示例

转载 作者:知者 更新时间:2024-03-23 19:11:05 25 4
gpt4 key购买 nike

本文整理了Java中org.apache.commons.configuration2.XMLConfiguration类的一些代码示例,展示了XMLConfiguration类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。XMLConfiguration类的具体详情如下:
包路径:org.apache.commons.configuration2.XMLConfiguration
类名称:XMLConfiguration

XMLConfiguration介绍

[英]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 scalarproperty 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, XMLConfigurationuses 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 FileBasedConfigurationinterface 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.
[中]一个专门的层次结构配置类,能够解析XML文档。
解析后的文档将保持其结构。该类还试图从加载的XML文档中保留尽可能多的信息,包括注释和处理指令。它们也将包含在save()方法创建的文档中。
与其他基于文件的配置类一样,该类维护加载的配置文件的名称和路径。可以使用几个setter方法更改这些属性,但save()和load()方法不会修改它们。如果XML文档包含到其他文档(例如到DTD)的相对路径,这些引用将基于为此配置设置的路径进行解析。
通过继承AbstractConfiguration,该类提供了一些扩展功能,例如属性值的插值。与PropertiesConfiguration中一样,属性值可以包含分隔符(逗号“,”每个默认值),然后拆分为多个值。这也适用于XML属性和元素的文本内容。分隔符可以用反斜杠转义。作为一个例子,考虑下面的XML片段:

<config> 
<array>10,20,30,40</array> 
<scalar>3\,1415</scalar> 
<cite text="To be or not to be\, this is the question!"/> 
</config>

在这里,数组元素的内容将在逗号处拆分,因此数组键将被分配4个值。在cite元素的scalarproperty和text属性中,逗号被转义,因此不执行拆分。
配置API允许为单个属性设置多个值,例如,以下内容是合法的(假设使用默认表达式引擎):

XMLConfiguration config = new XMLConfiguration(); 
config.addProperty("test.dir[@name]", "C:\\Temp\\"); 
config.addProperty("test.dir[@name]", "D:\\Data\\");

然而,在XML中,这样的星座是不受支持的;对于单个元素,属性只能出现一次。因此,试图保存违反此条件的配置将引发异常。
与其他配置实现一样,XMLConfiguration使用ListDelimiterHandler对象来控制列表拆分操作。默认情况下,会设置一个列表分隔符处理程序对象来禁用此功能。XML内置了对复杂结构的支持,包括列表属性;因此,列表拆分与此配置类型无关。不过,通过设置一个替代的ListDelimiterHandler实现,可以启用此功能。它与任何其他具体的配置实现一样有效。
默认情况下,XML文档内容中的空白会被删除。在大多数情况下,这是需要的。然而,有时空格的确很重要,应该被视为财产价值的一部分,如下例所示:

<indent>    </indent>

默认情况下,缩进元素中的空格将被修剪,从而生成一个空元素。为了告诉XMLConfiguration空间是相关的,可以使用XML specification中定义的xml:space属性。这将如下所示:

<indent xml:space="preserve">    </indent>

缩进属性的值现在将包含空格。
XMLConfiguration实现了FileBasedConfiguration接口,因此可以与基于文件的生成器一起使用,从各种源(如文件、URL或流)加载XML配置文件。
与其他配置实现一样,此类使用同步器对象来控制并发访问。通过选择同步器接口的合适实现,实例可以是线程安全的,也可以不是线程安全的。请注意,对通常通过生成器设置的大多数属性的访问不受同步器的保护。预期用途是,这些属性在构建时通过构建器设置一次,之后保持不变。如果希望在实例的生命周期内更改此类属性,则必须手动使用lock()和unlock()方法,以确保其他线程看到您的更改。
有关XMLConfiguration支持的基本功能的更多信息,可以在Basic features and AbstractConfiguration的《用户指南》中找到。另外还有一章专门讨论{{2$}。

代码示例

代码示例来源:origin: org.apache.commons/commons-configuration2

/**
 * Sets the name of the root element. This name is used when this
 * configuration object is stored in an XML file. Note that setting the name
 * of the root element works only if this configuration has been newly
 * created. If the configuration was loaded from an XML file, the name
 * cannot be changed and an {@code UnsupportedOperationException}
 * exception is thrown. Whether this configuration has been loaded from an
 * XML document or not can be found out using the {@code getDocument()}
 * method.
 *
 * @param name the name of the root element
 */
public void setRootElementName(final String name)
{
  beginRead(true);
  try
  {
    if (getDocument() != null)
    {
      throw new UnsupportedOperationException(
          "The name of the root element "
              + "cannot be changed when loaded from an XML document!");
    }
    rootElementName = name;
  }
  finally
  {
    endRead();
  }
}

代码示例来源:origin: org.apache.commons/commons-configuration2

/**
 * Sets the public ID of the DOCTYPE declaration. When this configuration is
 * saved, a DOCTYPE declaration will be constructed that contains this
 * public ID.
 *
 * @param publicID the public ID
 * @since 1.3
 */
public void setPublicID(final String publicID)
{
  beginWrite(false);
  try
  {
    this.publicID = publicID;
  }
  finally
  {
    endWrite();
  }
}

代码示例来源:origin: org.apache.commons/commons-configuration2

/**
 * Checks whether an element defines a complete list. If this is the case,
 * extended list handling can be applied.
 *
 * @param element the element to be checked
 * @return a flag whether this is the only element defining the list
 */
private static boolean isSingleElementList(final Element element)
{
  final Node parentNode = element.getParentNode();
  return countChildElements(parentNode, element.getTagName()) == 1;
}

代码示例来源:origin: org.apache.commons/commons-configuration2

/**
 * Returns the public ID of the DOCTYPE declaration from the loaded XML
 * document. This is <b>null</b> if no document has been loaded yet or if
 * the document does not contain a DOCTYPE declaration with a public ID.
 *
 * @return the public ID
 * @since 1.3
 */
public String getPublicID()
{
  beginRead(false);
  try
  {
    return publicID;
  }
  finally
  {
    endRead();
  }
}

代码示例来源:origin: org.apache.commons/commons-configuration2

beginWrite(false);
try
  final Transformer transformer = createTransformer();
  final Source source = new DOMSource(createDocument());
  final StringWriter writer = new StringWriter();
  final Result result = new StreamResult(writer);
  XMLDocumentHelper.transform(transformer, source, result);
  final Reader reader = new StringReader(writer.getBuffer().toString());
  final DocumentBuilder builder = createDocumentBuilder();
  builder.parse(new InputSource(reader));
  endWrite();

代码示例来源:origin: org.apache.commons/commons-configuration2

final Map<ImmutableNode, Object> elemRefs, final boolean trim, final int level)
final boolean trimFlag = shouldTrim(element, trim);
final Map<String, String> attributes = processAttributes(element);
attributes.put(ATTR_SPACE_INTERNAL, String.valueOf(trimFlag));
final StringBuilder buffer = new StringBuilder();
        new MutableObject<>();
    final Map<String, String> attrmap =
        constructHierarchy(childNode, refChildValue, child,
            elemRefs, trimFlag, level + 1);
    final Boolean childTrim = Boolean.valueOf(attrmap.remove(ATTR_SPACE_INTERNAL));
    childNode.addAttributes(attrmap);
    final ImmutableNode newChild =
        createChildNodeWithValue(node, childNode, child,
            refChildValue.getValue(),
            childTrim.booleanValue(), attrmap, elemRefs);
final String text = determineValue(buffer.toString(), childrenFlag, trimFlag);
if (text.length() > 0 || (!childrenFlag && level != 0))

代码示例来源:origin: com.goldmansachs.obevo/obevo-core

if (sysCfg.containsKey(ignorableAttribute)) {
    sysCfg.clearProperty(ignorableAttribute);
  if (!sysCfg.configurationsAt(ignorableSysNode).isEmpty()) {
    sysCfg.clearTree(ignorableSysNode);
  sysCfg.clearProperty("environments.environment[@" + ignorableAttribute + "]");
  sysCfg.clearProperty("environments.dbEnvironment[@" + ignorableAttribute + "]");
  sysCfg.clearTree("environments.environment." + ignorableSysNode);
  sysCfg.clearTree("environments.dbEnvironment." + ignorableSysNode);
ImmutableList<HierarchicalConfiguration<ImmutableNode>> envConfigs = ListAdapter.adapt(sysCfg.configurationsAt("environments.dbEnvironment")).toImmutable();
if (envConfigs.isEmpty()) {
  envConfigs = ListAdapter.adapt(sysCfg.configurationsAt("environments.environment")).toImmutable();

代码示例来源:origin: org.apache.commons/commons-configuration2

/**
 * Initializes this configuration from an XML document.
 *
 * @param docHelper the helper object with the document to be parsed
 * @param elemRefs a flag whether references to the XML elements should be set
 */
private void initProperties(final XMLDocumentHelper docHelper, final boolean elemRefs)
{
  final Document document = docHelper.getDocument();
  setPublicID(docHelper.getSourcePublicID());
  setSystemID(docHelper.getSourceSystemID());
  final ImmutableNode.Builder rootBuilder = new ImmutableNode.Builder();
  final MutableObject<String> rootValue = new MutableObject<>();
  final Map<ImmutableNode, Object> elemRefMap =
      elemRefs ? new HashMap<>() : null;
  final Map<String, String> attributes =
      constructHierarchy(rootBuilder, rootValue,
          document.getDocumentElement(), elemRefMap, true, 0);
  attributes.remove(ATTR_SPACE_INTERNAL);
  final ImmutableNode top =
      rootBuilder.value(rootValue.getValue())
          .addAttributes(attributes).create();
  getSubConfigurationParentModel().mergeRoot(top,
      document.getDocumentElement().getTagName(), elemRefMap,
      elemRefs ? docHelper : null, this);
}

代码示例来源:origin: com.airlenet/play-config

subConfig = new XMLConfiguration();

代码示例来源:origin: goldmansachs/obevo

if (sysCfg.containsKey(ignorableAttribute)) {
    sysCfg.clearProperty(ignorableAttribute);
  if (!sysCfg.configurationsAt(ignorableSysNode).isEmpty()) {
    sysCfg.clearTree(ignorableSysNode);
  sysCfg.clearProperty("environments.environment[@" + ignorableAttribute + "]");
  sysCfg.clearProperty("environments.dbEnvironment[@" + ignorableAttribute + "]");
  sysCfg.clearTree("environments.environment." + ignorableSysNode);
  sysCfg.clearTree("environments.dbEnvironment." + ignorableSysNode);
ImmutableList<HierarchicalConfiguration<ImmutableNode>> envConfigs = ListAdapter.adapt(sysCfg.configurationsAt("environments.dbEnvironment")).toImmutable();
if (envConfigs.isEmpty()) {
  envConfigs = ListAdapter.adapt(sysCfg.configurationsAt("environments.environment")).toImmutable();

代码示例来源:origin: org.apache.commons/commons-configuration2

/**
 * Returns the system ID of the DOCTYPE declaration from the loaded XML
 * document. This is <b>null</b> if no document has been loaded yet or if
 * the document does not contain a DOCTYPE declaration with a system ID.
 *
 * @return the system ID
 * @since 1.3
 */
public String getSystemID()
{
  beginRead(false);
  try
  {
    return systemID;
  }
  finally
  {
    endRead();
  }
}

代码示例来源:origin: org.apache.commons/commons-configuration2

/**
 * Sets the system ID of the DOCTYPE declaration. When this configuration is
 * saved, a DOCTYPE declaration will be constructed that contains this
 * system ID.
 *
 * @param systemID the system ID
 * @since 1.3
 */
public void setSystemID(final String systemID)
{
  beginWrite(false);
  try
  {
    this.systemID = systemID;
  }
  finally
  {
    endWrite();
  }
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com