I only want to add that you can apply partionally unmarshalling by JAXB
, but it can be accosiated with some problems.
For example i used the same partionally unmarshalling (but i parsed my XML
with XMLStreamReader
, not XMLEventReader
) with the follow XSD
:
<xs:element name="Payload">
<xs:complexType>
<xs:sequence>
<xs:element name="Cities">
<xs:complexType>
<xs:sequence minOccurs="1" maxOccurs="unbounded">
<xs:element name="City">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute type="xs:ID" name="id" use="required"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Users">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="User">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="email"/>
<xs:attribute type="xs:IDREF" name="city" use="required"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
And i used partionally unmarshalling by JAXB
for User
objects which are related with cities. But there was not city in the unmarshalled user:
User user = unmarshaller.unmarshal(xsr, User.class);
user.getCity().getId() // throws NullPointerException
Apparently JAXB
just does not see earlier cities objects in the parsing XML
so i should use the follow workaround:
String cityId = xsr.getAttributeValue(null, "city")
User user = unmarshaller.unmarshal(xsr, User.class);
At last i had read the javadoc for the method Unmarshaller#unmarshal(javax.xml.stream.XMLStreamReader reader, Class<T> declaredType)
:
Unmarshal root element to JAXB mapped declaredType and return the resulting content tree.
This method implements unmarshal by declaredType.
This method assumes that the parser is on a START_DOCUMENT or START_ELEMENT event.
Unmarshalling will be done from this start event to the corresponding end event.
If this method returns successfully, the reader will be pointing at the token right after the end event.
Apparently the method is not supposed for such using and you should pay much attention when you use the methoud by this way.