2

我正在使用@XmlRootElement注释以及@XmlElement在我的 Spring MVC 应用程序中生成 xml 输出。我有以下课程:

@XmlRootElement
public class Chart
{
    private String id;
    private String name;
    private List<Connection> connections;
    //..................

    @XmlElement(name = "connection")
    public List<Connection> getConnections()
    {
        return this.connections;
    }

    //..................
}

public class Connection
{
    private String from;
    private String to;

    public String getFrom()
    {
        return this.from;
    }

    public void setFrom(String from)
    {
        this.from = from;
    }

    public String getTo()
    {
        return this.to;
    }

    public void setTo(String to)
    {
        this.to = to;
    }
}   

我得到这样的 xml 输出:

<chart>
    <id>a1</id>
    <name>chart1</name>
    <connection>
        <from>a1</from>
        <to>a2</to>
    </connection>
    ....
</chart>

但是,我需要以这种方式格式化 xml:

<chart>
    <id>a1</id>
    <name>chart1</name>
    <connection from="a1" to="a2"></connection>
    ....
</chart>

如何配置注释以实现此结果?

4

1 回答 1

2

用于您要视为属性@XmlAttribute的特定元素。Connection

public class Connection
{
    private String from;
    private String to;

    public String getFrom()
    {
        return this.from;
    }

    @XmlAttribute
    public void setFrom(String from)
    {
        this.from = from;
    }

    public String getTo()
    {
        return this.to;
    }

    @XmlAttribute
    public void setTo(String to)
    {
        this.to = to;
    }
}
于 2013-01-06T22:36:44.903 回答