reading/storing configuration

Hi,

I’m trying to read a config file like this:

<MapRules>
	<Rule>
		<Name>TerrainsToBeFoggedWithinLos</Name>
		<Value>FOREST</Price>
	</Rule>
	<Rule>
		<Name>BuildingsToBeFoggedWithinLos</Name>
		<Value>CITY,FACTORY,PORT</Price>
	</Rule>
	<Rule>
		<Name>FogOn</Name>
		<Value>true</Price>
	</Rule>	
</MapRules>

I know howto read it out the xml file(using org.w3c.dom) ,
but I don’t know how to store it(in a good way) into java

I want to get the correct type, support lists

If i would create a hashmap:

  private static HashMap<String, Object> rules;

  public static Object getRule(String rule) {
    return rules.get(rule);
  }

Then my ide complains that it is unsafe to get it directly
List foggedTerrains = (List) Rules.getRule(“TerrainsToBeFoggedWithinLos”);
List foggedBuildings = (List) Rules.getRule(“BuildingsToBeFoggedWithinLos”);

Should I create getInt, getByte, getList ? or …

Properties is EXACT what you are looking for.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html

Very useful for configuration files and things like that.
But if you need to store large amounts of data, like retrieving the money every player has in your game, the price of each item of a store… You really should use a database like MySQL or PostgreSQL.

Well, properties are generally used for plain data rather then hierarchical. They are much easier to operate though.

If you want to use XML anyway you should refer to XStream (http://xstream.codehaus.org/) or Digester (http://commons.apache.org/digester/) (personally I prefer Digester). Try to use those libraries instead of core Java functionality to ease your life a bit.

He already knows how to read XML. He’s asking how he should store it.

The compiler is complaing about the unsafe cast. Change it to this:


List<TerrainType> foggedTerrains = (List<TerrainType>) Rules.getRule("TerrainsToBeFoggedWithinLos");
List<BuildingType> foggedBuildings = (List<BuildingType>) Rules.getRule("BuildingsToBeFoggedWithinLos");

The issue is with generics. Generics trys to make your code more robust by only allowing the type defined to be stored in a collection. You can bypass that by usig Object, but it is not recommended. It is more desirable to use a base class or interface and only put the same types in the same collection.

I found the successor of Properties,… Preferences!

stores/reads xml
it has getBoolean() amongst others.