Java JAXB - 获得预期的输出

时间:2017-01-12 12:31:39

标签: java xml jaxb

我试图以一种形式获得XML ile:

<?xml version="1.0" encoding="UTF-8"?>
<image>
    <lines>
        <line id="a">
            <coordinates x="297" y="44"/>
            <coordinates x="302" y="117"/>          
        </line >
        <line id="b">
            <coordinates x="42" y="111"/>
            <coordinates x="48" y="131"/>
            <coordinates x="39" y="142"/>           
        </line >
    </lines>
</image>

我有两个类:LineWrapper和Line:

LineWrapper:

@XmlRootElement(name = "image")
public class LineWrapper {

    private List<Line> lines;

    @XmlElementWrapper(name = "lines")
    @XmlElement(name = "line")
    public List<Line> getLines() {
        return lines;
    }
    (...)
}

行:

public class Line{
    (...)
    @XmlAttribute(name = "id")
    public String getId() {
        return id.get();
    }

    @XmlAttribute(name="x")
    public List<Integer> getxList() {
        return xList;
    }

    @XmlAttribute(name="y")
    public List<Integer> getyList() {
        return yList;
    }   
}

我用这样的注释获得的是:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<image>
    <lines>
        <line id="a" x="297 302" y="44 117"/>
        <line id="b" x="44 48 39" y="111 131 142"/>
    </lines>
</image>

如何制作额外的标签&#39;坐标&#39;对于x和y的属性对?

1 个答案:

答案 0 :(得分:0)

创建一个包含x和y值的Coordinates类:

public class Coordinates{
    (...)

    private int x;
    private int y;


    @XmlAttribute(name="x")
    public int getX() {
        return x;
    }

    @XmlAttribute(name="y")
    public int getY() {
        return y;
    } 


}

然后修改您的Line类以使用此列表作为元素,而不是拥有x和y值:

public class Line{
    (...)

    private List<Coordinates> coordinatesList = new ArrayList<Coordinates>;

    @XmlAttribute(name = "id")
    public String getId() {
        return id.get();
    }

    @XmlElement(name = "coordinates")
    public List<Coordinates> getCoordinatesList() {
        return coordinatesList;
    }



}

当然,您必须创建正确的Coordinates个对象(此示例中缺少setter方法),并用它们填充Line个对象。