I've recently had a requirement to unmarshal an XML
fragment that was passed into one of my services. This in itself is typically not and issue and I've written code that does that plenty a time, however in this case I was having to unmarshal a fragment for a complex type
, not for an element
. That's where it got a little bit more complicated.
Initially my code was throwing the following exception:
So that meant that the unmarshaller didn't recognise any valid elements in my XML
string that I was trying to unmarshal. I checked the JAXB Context
and it definitely had the complex type I was after so it was something else I was doing wrong.
Lets take a step back and look at the schema, my complex type, MyComplexType
, was defined as:
That resulted in a JAXB generated class
that looked like:
So, no XmlRootElement
annotation. That's because it was a complex type
and not an element
of that type. That should have been obvious right away, but I missed it initially. Luckily there was a simple way around it. All I had to do was tell JAXB
what complex type I was expecting and wrap the XML fragment
as a Source
or specifically StreamSource
So the code that would achieve that looked something like...
That worked like a charm and I could then get my unmarshalled complex type instance from the JAXBElement
Hope you found this post useful...
...so please read on! I love writing articles that provide beneficial information,
tips and examples to my readers. All information on my blog is provided free of
charge and I encourage you to share it as you wish. There is a small favour I ask in return however -
engage in comments below, provide feedback, and if you see mistakes let me know.
If you want to show additional support and help me pay for web hosting and
domain name registration,
donations, no matter how small, are always welcome!
Use of any information contained in this blog post/article is subject to this disclaimer
Other posts you may like...