JAXB Marshall / Unmarshall具有List变量成员的类对象

时间:2016-07-22 01:21:13

标签: java xml list jaxb

我正在尝试使用JAXB加载一系列XML文件,为每个类创建几个对象列表。

瓷砖等级

import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement//(name="Tiles")
@XmlAccessorType(XmlAccessType.FIELD)
public class Tile {

    private String name;
    public String getName(){
        return name;
    }
    public void  setName(String arg){
        this.name = arg;
    }

    private int id;
    public int getId() {
        return id;
    }
    public void setId(int arg){
        this.id = arg;
    }

    private String imageName;
    public String getImageName(){
        return imageName;
    }
    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    private int drawType;
    public int getDrawType(){
        return drawType;
    }
    public void setDrawType(int drawType) {
        this.drawType = drawType;
    }

    private int trueType;
    public int getTrueType() {
        return trueType;
    }
    public void setTrueType(int trueType) {
        this.trueType = trueType;
    }

    private int count;
    public int getCount(){
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }

    private List<Integer> side;
    public Integer getSide(int arg){
        return side.get(arg);
    }
    public void setSide(List<Integer> side) {
        this.side = side;
    }

    private int feature;
    public int getFeature (){
        return feature;
    }
    public void setFeature(int feature) {
        this.feature = feature;
    }
 }

因此,虽然我真的想要解组XML,但我认为首先要对该类的测试实例进行Marshal,以确认生成的XML文件的格式。

JAXBContext jc = JAXBContext.newInstance(Tile.class,JAXB2_Lists.class,Feature.class );

JAXB2_Lists<Tile> exportTest = new JAXB2_Lists<>();
Marshaller marshaller = jc.createMarshaller();

Tile testTile = new Tile();
testTile.setCount(1);
testTile.setDrawType(1);
testTile.setFeature(1);
testTile.setId(1);
testTile.setImageName("TestImage.png");
testTile.setName("Test Name");
testTile.setTrueType(1);
List<Integer> sides = new ArrayList<>();
testTile.setSide(sides);

exportTest.getValues().add(testTile);

marshaller.marshal(exportTest, new File("TilesExport.xml"));

生成的XML如下所示。

<jaxb2Lists>
    <tile>
        <name>Test Name</name>
        <id>1</id>
        <imageName>TestImage.png</imageName>
        <drawType>1</drawType>
        <trueType>1</trueType>
        <count>1</count>
        <feature>1</feature>
    </tile>
</jaxb2Lists>

JAXB_List类在以下URL中详述,这是我的另一个问题。 (没有人显然有答案。 https://stackoverflow.com/questions/38472060/dynamic-xmlrootelement-name

因此,生成的XML具有除Sides成员变量之外的所有值。

我哪里错了?

1 个答案:

答案 0 :(得分:1)

您的sides列表需要公共getter,并且setter需要命名为sides。类似的东西:

public List<Integer> getSides() {
    return side;
}
public void setSides(List<Integer> sides) {
    this.side = sides;
}

应该这样做。为了保持一致,可能还值得将side字段重命名为sides