使用XStream读取XML对象时,如果我不知道XML将包含多少个字段,该怎么办?

问题描述:

我已经建立了一个从XML读取的系统,但是我需要在向它读取XML之前手动构建对象。使用XStream读取XML对象时,如果我不知道XML将包含多少个字段,该怎么办?

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> 

如何建立对象:

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 

} 

但我应该做的字段随机算什么。如果XML中有2个<color>字段,我会阅读。如何实现这个自动化?

通常,XStream对象具有代表XML中字段的字段。请参阅Person - XStream tutorial中的对象。

如果您有这种类型的对象,我认为您应该能够使用@XStreamImplicit注解color属性来处理XML中的多个出现。

某处沿着这个未经测试的代码行:

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; 

}