Working with XML has always been a mess in java...
This is what took me many hours (again) to find out today... This is what does the magic of avoiding the need of manually or complicated configurative (e.g. via plugins in pom.xml or xjb files etc.) adding of @XmlRootElement annotations:
XmlParserFactory.saxNamespaceAwareSourceOf
Main reason: I generated the client code for Kafka messages via jaxb2-maven-plugin and did NOT want to modify them manually.
My code:
# imagine TYPE_TO_CHECK to be some generic type
# and typeToCheck the Class<TYPE_TO_CHECK>
TYPE_TO_CHECK converted = Optional.ofNullable(
JAXBContext.newInstance(typeToCheck).createUnmarshaller()
.unmarshal(
// this avoids the need of XmlRootElement, too :-)
XmlParserFactory.saxNamespaceAwareSourceOf(message),
typeToCheck
)
).map(JAXBElement::getValue).orElse(null);