I am having a problem with JAXB and Unmarshalling the following XML
<ns2:ID entry-method="manual"> 123456789012345678
<ns2:ID2>123456789012345678</ns2:ID2>
</ns2:ID>
I obtained the schema and using the the JAXB xjc tool it generated the following property definition:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"ID1",
"ID2",
"ID3"
})
@XmlRootElement(name = "ID")
public class ID {
@XmlElement(name = "ID1")
protected String id1;
@XmlElement(name = "ID2")
protected String id2;
@XmlElement(name = "ID3")
protected String id3;
@XmlAttribute(name = "entryMethod")
protected String entryMethod;
public String getId1() {
return id1
}
public void setId1(String value) {
this.id1 = value;
}
public String getId2() {
return id2
}
public void setId2(String value) {
this.id2 = value;
}
public String getId3() {
return id3;
}
public void setId3(String value) {
this.id3 = value;
}
public String getEntryMethod() {
if (entryMethod == null) {
return "swipe";
} else {
return entryMethod;
}
}
public void setEntryMethod(String value) {
this.entryMethod = value;
}
}
As you can see the device that is sending the XML does not include the ID1 tag it merely adds the ID1 data as the value of the root tag. When Unmarshalling this Xml any calls to getID1 return null. I am confused on what annotations to use to alter the class to support the data in the root tag to be assigned to the id1 field.
Any ideas on what annotation changes would make this work?
This is the correct XML schema content (omitting namespace) for your XML:
<xs:element name="ID" type="IdType"/>
<xs:complexType name="IdType" mixed="true">
<xs:sequence>
<xs:element name="id2" type="xs:string"/>
<xs:element name="id3" type="xs:string"/>
</xs:sequence>
<xs:attribute name="entry-method" type="xs:string"/>
</xs:complexType>
The sad consequence is that the generated class IdType contains
public List<Serializable> getContent() {
if (content == null) {
content = new ArrayList<Serializable>();
}
return this.content;
}
for containing the ID text child (children!) and all the ID element children. So, the processing of an ID might be something like:
JAXBElement<IdType> jbe =
(JAXBElement<IdType>)u.unmarshal( new File( "mixed.xml" ) );
for( Object obj: jbe.getValue().getContent() ){
System.out.println( obj.getClass() + " " + obj );
if( obj instanceof String ){
// text child (even the blank space
} else if( obj instanceof JAXBElement ){
// process an element child wrapped into JAXBElement
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With