Collections and Maps

When creating Collections or Abstract Maps, XJConf is able to call the add() or put() method and pass the appropriate parameters automatically.

Collections

Creating collections like an ArrayList? is extremely easy:

<defines>
  <tag name="list" type="java.util.ArrayList"/>
  <tag name="entry" type="java.lang.String" key="__none"/>
</defines>

Using the key none will tell XJConf, that it should check, whether the parent object is a Collection and than pass the value of the current tag to the add() method. So you can parse the following file with this tag definition:

<configuration>
  <list>
    <entry>one</entry>
    <entry>two</entry>
    <entry>three</entry>
  </list>
</configuration>

If you now fetch the value for list, you will get an ArrayList? that is filled with three String objects.

HashMaps?

XJConf will also detect, whether a class extends java.util.AbstractMap? or java.util.Properties and will automatically call the appropriate put() or setProperty method:

<defines>
    <tag name="properties" type="java.util.Properties"/>
    <tag name="map" type="java.util.HashMap"/>
    <tag name="prop" type="java.lang.String" keyAttribute="name"/>
</defines>

After defining these tags as a HashMap? and Properties you can use them in your XML documents:

<configuration>
    <map>
        <prop name="foo">bar</prop>
        <prop name="argh">tomato</prop>
    </map>

    <properties>
        <prop name="foo">bar</prop>
        <prop name="argh">tomato</prop>
    </properties>
</configuration>

The XML document needs to be parsed in the same manner as always:

import net.schst.xjconf.*;

DefinitionParser tagParser = new DefinitionParser();
NamespaceDefinitions defs = tagParser.parse("xml/defines-hashmap.xml");

XmlReader conf = new XmlReader();
conf.setTagDefinitions(defs);

try {
    conf.parse("xml/hashmap.xml");
} catch (Exception e) {
    e.printStackTrace();
    System.exit(0);
}
        
HashMap map = (HashMap)conf.getConfigValue("map");
System.out.println(map);

Properties props = (Properties)conf.getConfigValue("properties");
System.out.println(props);