Reputation: 2472
I have a use case where in some cases (dependant on business logic) we want to not display some XML elements. So I can't use @XmlTransient (i think).
I'd like to do something like this.
private void HideSome() {
// some code to hide a specific element
}
Upvotes: 1
Views: 1550
Reputation: 385
You should define the element not required in annotations and the corresponding XSD as optional (minOccurs=0 maxOccurs=1).
If you do not want it rendered, set it to null before passing it to the marshaller.
xsd
<complexType name="MyElementType">
<sequence>
<element name="ID" type="string" />
<element name="MaybeHere" type="string" minOccurs="0" maxOccurs="1" />
</sequence>
</complexType>
<element name="MyElement" type="MyElementType" />
java
@XmlRootElement(name="MyElement")
public class MyElement {
private String id;
private String maybeHere;
@XmlElement(name="ID")
public String getId() {return id;}
public void setId(String s){this.id = s;}
@XmlElement(name="MaybeHere", required=false)
public String getMaybeHere() {return maybeHere;}
public void setMaybeHere(String s) { this.maybeHere = s;}
}
marshalling
/* in some code */
if(businessCondition){
myElem.maybeHere = null;
}
marshaller.marshal(myElem);
Upvotes: 2