Reputation: 6124
I have a following sample xsd
<annotation><appinfo>
<jaxb:schemaBindings>
<jaxb:package name="com.myapp"/>
</jaxb:schemaBindings>
</appinfo></annotation>
<element name="user">
<complexType>
<sequence>
<element name="roles" type="u:Roles" minOccurs="1"></element>
</sequence>
<attribute name="name" type="string"></attribute>
</complexType>
</element>
<complexType name="Role">
<complexContent>
<extension base="u:Role">
<attribute name="name" type="string"></attribute>
<attribute name="action" type="string"></attribute>
</extension>
</complexContent>
</complexType>
I want to unmarshall only a Roles xml like the sample as follows
JAXBContext c = JAXBContext.newInstance(User.class, Roles.class, Role.class);
Unmarshaller unmarshaller = c.createUnmarshaller();
JAXBElement ele = (JAXBElement) unmarshaller.unmarshal(inputStream);
return (Roles) ele.getValue();
My input stream/xml is
<roles>
<role name="admin" action="all"/>
<role name="recep" action="select"/>
</roles>
The above code throws the following error
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.myapp.com/xsd/internal/myapp", local:"roles"). Expected elements are <{http://www.myapp.com/xsd/internal/myapp}User>
How to get my roles xml to be unmarshall?
Upvotes: 0
Views: 553
Reputation: 43699
If you know the class you want to unmarshal, use the unmarshal(Source source, Class<T> declaredType)
and likes.
So try unmarshaller.unmarshall(source, Roles.class)
which would give you JAXBElement<Roles>
. You can then getValue()
from it to get an instance of Roles
.
If you provide the class for unmarshalling, the root element name does not matter at all, JAXB does not neet to "know" it.
Upvotes: 1