簡體   English   中英

使用XStream讀取XML進行對象處理時,如果我不知道XML將具有多少個字段怎么辦?

[英]While using XStream to read XML to object, what if I don't know how many fields the XML will have?

我已經設置了一個從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中字段的字段。 請參閱XStream教程中Person object。

如果您有這種類型的對象,我認為您應該能夠使用@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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM