1. 程式人生 > >JAXBContext 設定xml節點屬性

JAXBContext 設定xml節點屬性

在使用JAXBContext將javaBean轉化為xml時,會出現這樣的需求:

<xml version="2.0">
    ....
</xml>

那麼xml節點裡的屬性值version需要怎麼設定,使用@XmlAttribute標籤即可,如下程式碼。

@XmlRootElement(name = "Xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class RequestBean{
	
    @XmlAttribute(name = "version") //設定節點屬性
    private String version;

    private Body body; 
        
    @XmlElement(name = "sign")  //設定子節點
    private String sign;	
    //省略封裝
}

@XmlRootElement(name = "Body")
@XmlAccessorType(XmlAccessType.FIELD)
public class Body{
    ...
}

最終得到的xml檔案大致為:

<Xml version="2.0">
    <sign>111111</sign>
    <Body>
	<Amount>111</Amount>
	<Fee>fee</Fee>
	<PayerName>payname</PayerName>
	<AccountType>accountType</AccountType>
    </Body>
</Xml>