views:

558

answers:

6

I've got a simple java class that looks something like this:

public class Skin implements Serializable {

 public String scoreFontName = "TahomaBold";
 ...
 public int scoreFontHeight = 20;
 ...
 public int blockSize = 16;
            ...

 public int[] nextBlockX = {205, 205, 205, 205};
            ...
 public String backgroundFile = "back.bmp";
            ... 
}



I'd like to read this information from a simple XML file that looks something like this:

<xml>
    <skin>
        <scoreFontName>"Tahoma Bold"</scoreFontName>
        ...
        <scoreFontHeight>20</scoreFontHeight>
        ...
        <blockSize>16</blockSize>
        ...
        <nextBlockX>
             <0>205</0>
             <1>205</1>
             <2>205</2>
             <3>205</3>
        <nextBlockX>
        ....
        <backgroundFile>"back.bmp"</backgroundFile>
        ...
     <skin>
 </xml>

Is there an easy way to inject the information from the xml file directly into the variable names rather than having to parse it manually? I don't mind using an external library.

Any help is appreciated.

+6  A: 

XStream is really great library for just this.

http://xstream.codehaus.org/

You can set up aliases for your class and even custom data formats to make the XML file more readable.

MarcusO
I use Xstream for quite a few things. I like that it is easy to extend so that you make the file look the way you want.
Jay R.
A: 

Thanks Marcus. That's exactly what I was looking for.

JoshuaD
+1  A: 

I would actually recommend Apache Digester, since if your classes are beans, it will just handle reading the XML into them.

Uri
A: 

Here's a quick question for Marcus, or anyone who's familiar with XStream: Is it possible to change it's output format so it uses a tab rather than 2 spaces?

JoshuaD
You should post this as a separate question.
Jay R.
+1  A: 

Alternatives to the already mentioned solutions (XStream and Apache Commons Digester) would be Java's own JAXB for a comparable general approach, or solutions more tailored towards configuration like Apache Commons Configuration or Java's Preferences API.

Fabian Steeg
+1  A: 

You can also use Spring - although it may be a bit of overkill for one class if its for a mobile game!

Fortyrunner