I haven't been able to reproduce what you are seeing. Below is what I have tried.
Java Model
Simple
Below is what I implemented for your Simple
class.
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Simple", propOrder = {
"content"})
public class Simple extends Valor{
@XmlElements({
@XmlElement(name="content",type=String.class),
@XmlElement(name="content",type=Integer.class),
})
protected Object content;
public Object getContent() {
return content;
}
@Override
public String getValorString() {
throw new UnsupportedOperationException();
}
public void setContent(Object content) {
this.content = content;
}
}
Demo Code
input.xml
Below is the input document with the close tag for content
corrected.
<simple>
<content>
123456
</content>
</simple>
Demo
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Simple.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource source = new StreamSource("src/forum22911170/input.xml");
Simple simple = unmarshaller.unmarshal(source, Simple.class).getValue();
System.out.println(simple.getContent());
}
}
Output
Below is the output from running the demo code:
123456
UPDATE
The problem you are running into is that you have both options in the @XmlElements
annotation mapped to the same element content
. For unmarshalling JAXB will treat the element based on the first @XmlElement
with that name. In the case below it will always treat it as a String
, it you reversed the order it would always treat it as an Integer
.
@XmlElements({
@XmlElement(name="content",type=String.class),
@XmlElement(name="content",type=Integer.class),
})
protected Object content;
The proper usage is to have them mapped to different elements such as
@XmlElements({
@XmlElement(name="FOO",type=String.class),
@XmlElement(name="BAR",type=Integer.class),
})
protected Object content;