I've set up a system to read from XML but I need to build the object manually before reading XML to it.
XML:
<actor id="" PGFVersion="" GSCVersion="">
<attributes>
<text id="name">Actor 1</text>
<real id="time">0</real>
<point id="position">
<real id="x">0</real>
<real id="y">0</real>
</point>
<size id="size">
<real id="width">0</real>
<real id="height">0</real>
</size>
<angle id="rotation">0</angle>
<color id="color">
<real id="red">0</real>
<real id="green">0</real>
<real id="blue">0</real>
<real id="alpha">0</real>
</color>
<image id="image">0</image>
<text id="tags">tag1 tag2</text>
<boolean id="preloadArt">true</boolean>
</attributes>
</actor>
How I set-up the object:
public class Attributes {
@XStreamImplicit
public List fields = new ArrayList();
public Attributes(){
this.addText("name", "Actor 1");
this.addReal("time", "0");
this.addPoint("position", "0", "0");
this.addSize("0", "0");
this.addAngle("rotation", "0");
this.addColor("0", "0", "0", "0");
this.addImage("0");
this.addText("tags", "tag1 tag2");
this.addBoolean("preloadArt","true");
}
public void addText(String id, String value){
Text text = new Text(id,value);
this.fields.add(text);
}
//other adders
}
But what should I do with random count of fields. What if there are 2 <color>
fields on the XML I'll read. How to automate this?
Usually the XStream object have fields representing the fields in the XML. See the Person
-object in the XStream tutorial.
If you have this type of object, I think you should be able to annotate the color
property with @XStreamImplicit
to handle multiple occurences in the XML.
Somewhere along the lines of this untested code:
public class Attributes {
// 'name' and 'text' occurs only once.
public String name;
public String text;
public Size size;
// The other attributes
// color can occur multiple times.
@XStreamImplicit
public int color;
}