Reputation: 113
I am using JAXB API for mapping a Java object to XML. My Java class is
@XmlRootElement(name = "ad")
@XmlAccessorType(XmlAccessType.FIELD)
class Item {
@XmlElement(name = "id", nillable = false)
@XmlCDATA
private int id;
@XmlElement(name = "url", nillable = false)
@XmlCDATA
private String url;
public Item() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Output is like this :
<ad>
<id><![CDATA[ 104 ]]></id>
<url><![CDATA[www.google.com]]></url>
</ad>
I need to add an attribute to url element, for example :
<ad>
<id><![CDATA[ 104 ]]></id>
<url type="fr"><![CDATA[www.google.fr]]></url>
</ad>
I have tried many combinaisons using @XmlValue and @XmlAttribute ...
Upvotes: 1
Views: 1010
Reputation: 285415
Your url variable should not be a String, but should be its own type. You should create a separate class for the url item, Url, and give it a String field, type, with an @XmlAttribute
annotation.
For example,
@XmlRootElement(name = "ad")
@XmlAccessorType(XmlAccessType.FIELD)
class Item {
@XmlElement(name = "id")
private int id;
@XmlElement(name = "url")
private Url url;
public Item() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
// @XmlAttribute
public Url getUrl() {
return url;
}
public void setUrl(Url url) {
this.url = url;
}
}
@XmlRootElement(name = "url")
@XmlAccessorType(XmlAccessType.FIELD)
class Url {
@XmlValue
private String value;
@XmlAttribute(name = "type")
private String type;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Note that I don't have MOXY so I can't use or test your @XmlCDATA
annotation.
Upvotes: 1