问题
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.
回答1:
XStream is really great library for just this.
http://x-stream.github.io/
You can set up aliases for your class and even custom data formats to make the XML file more readable.
回答2:
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.
回答3:
I would actually recommend Apache Digester, since if your classes are beans, it will just handle reading the XML into them.
回答4:
You can also use Spring - although it may be a bit of overkill for one class if its for a mobile game!
回答5:
I've recently started using Simple http://simple.sourceforge.net/ for XML to object mapping. It uses annotations within the class similarly to method I use in C# and is nice and clean. You can also break up the file into multiple classes and loading saving is a simple one liner.
In your case the Class structure would look like.
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root (Name="skin")
public class Skin {
@Element(name="scoreFontName") // name param not needed if class field is the same as the xml (element) value
private String scoreFontName
@Element
private int scoreFontHeight
@Element
private int blockSize
@ElementArray
private int[] nextBlockX
@Element
private String backgroundFile
// getters
}
Note one difference is that your array will be saved like this
<nextBlockX>
<int>205</int>
<int>205</int>
<int>205</int>
<int>205</int>
<nextBlockX>
But you you have the option of adding (entry="myName") to the annotation in which came the XML will be saved down like this
<nextBlockX>
<myName>205</myName>
<myName>205</myName>
<myName>205</myName>
<myName>205</myName>
<nextBlockX>
But the end result is the same once it's loaded into the array.
回答6:
Use JAXB. It is included in the JDK starting with Java 1.6.
来源:https://stackoverflow.com/questions/501325/how-to-easily-load-a-xml-based-config-file-into-a-java-class