I want to unmarshall the following XML structure using JAXB:
<orCondition>
<andCondition>
<andCondition>
<simpleCondition value="val1" />
<simpleCondition value="val2" />
</andCondition>
<simpleCondition value="val3" />
</andCondition>
<simpleCondition value="val4" />
</orCondition>
I have the following Java classes:
Condition base class
@XmlType(name="condition")
public class Condition {
}
Composite class containing two conditions
@XmlType(name="composite")
public class Composite extends Condition {
@XmlElement(name = "condition", type = Condition.class)
private Condition firstCondition;
@XmlElement(name = "condition", type = Condition.class)
private Condition secondCondition;
public Condition getFirstCondition() {
return firstCondition;
}
public void setFirstCondition(Condition firstCondition) {
this.firstCondition = firstCondition;
}
public Condition getSecondCondition() {
return secondCondition;
}
public void setSecondCondition(Condition secondCondition) {
this.secondCondition = secondCondition;
}
}
And condition
@XmlType(name = "andCondition")
public class And extends Composite {
}
Or condition
@XmlType(name = "orCondition")
public class Or extends Composite {
}
Simple leaf class condition
@XmlType(name = "simpleCondition")
public class Simple extends Condition {
@XmlAttribute
String value;
}
This does not work. I have an instance variable in an other class that looks like this:
@XmlElement(name = "condition", type = Condition.class)
private Condition condition;
It stays null after unmarshalling. The rest of the object unmarshalls fine
Anny suggestions? Or is this not possible?
You could structure your model like:
Composite
You could change your
Compositeclass to look something like the following and use the@XmlElementRefannotation.@XmlElementRefcorresponds to the XML schema concept of substitution groups:Condition
And
For each of the subclasses that can appear in the XML you will need to annotate with
@XmlRootElement. This acts as the type identifier for the@XmlElementRefproperty.Or
Simple
Demo
Input/Output
For More Information