I have the following XML:
<ns2:Person name="John" age="20" />
And I want to unmarshal it to JAXB object Person which was generated from the XSD.
this is the code I'm running:
JAXBContext context = JAXBContext.newInstance(PersoEntity.class);
Unmarshaller um = context.createUnmarshaller();
StringReader sr = new StringReader(xml);
Person p = (Person)um.unmarshal(sr);
Surprisingly I get the following exception:
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException: The prefix "ns2" for element "ns2:Person" is not bound.]
How do I solve it? Thanks
Your best bet is probably to nest the desired element inside another element that binds the namespace. It doesn't really matter what you bind it to, just make it a valid XML document that will parse. Then you can unmarshal by declared type
GETTING THE FRAGMENT
The way that you are currently getting the XML fragment is causing the namespace declarations to be lost. In your fragment
ns2
is no longer a prefix, you just have a element name with a colon in it (ns2:Person
). This is going to cause problems with namespace aware parsers. The article below may be a better approach for you to get the XML fragment:HANDLING YOUR USE CASE
Using the XML fragment that you have, you could create an
XMLFilter
that removes the prefix from the XML element, and then leverage JAXB'sUnmarshallerHandler
to do the unmarshalling.Demo
PersonEntity