2013-01-06 93 views
2

我使用的是@XmlRootElement批註與@XmlElement一起產生在我的Spring MVC應用程序中的XML輸出的元素。我有以下類:生成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> 

如何配置註釋爲了達到這樣的結果?

回答

2

上要當作屬性Connection的特定元素使用@XmlAttribute

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; 
    } 
} 
+1

+1 - 不需要這個用例的'@ XmlType'註釋:http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html –

+1

@BlaiseDoughan,感謝您指出了這一點。我已經編輯了相應的答案。 – GargantuChet