UnmarshalException is thrown when parsing element <message id="123">.
The exception message is strange that
unexpected element is also shown in
expected element with same uri and name:
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.mydomain.com/myns", local:"message"). Expected elements are <{http://www.mydomain.com/myns}message>,<{http://www.mydomain.com/myns}type>,<{http://www.mydomain.com/myns}param>
My scenario is:
Target XML to unmarshal (missing xmlns):
<message id="123">
<type name="name">
<param>
</param>
</type>
</message>
The schema header is:
<xsd:schema targetNamespace="http://www.mydomain.com/myns" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.mydomain.com/myns" elementFormDefault="qualified">
My filter extends XMLFilterImpl and overrides startElement:
public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException {
super.startElement("http://www.mydomain.com/myns", localName, name, atts);
}
My code to do the unmarshal is:
JAXBContext jctx = JAXBContext.newInstance("my.package.name");
Unmarshaller um = jctx.createUnmarshaller();
SAXParserFactory spFactory = SAXParserFactory.newInstance();
spFactory.setNamespaceAware(true);
spFactory.setValidating(false);
SAXParser saxParser = spFactory.newSAXParser();
NsFilter nsFilter = new NsFilter(saxParser.getXMLReader());
nsFilter.setContentHandler(um.getUnmarshallerHandler());
SAXSource saxSource = new SAXSource(nsFilter, new InputSource(new ByteArrayInputStream(messageBytes)));
Object obj = um.unmarshal(saxSource);
Hope someone could help. Thanks.
P.S. I've also tried to manually add back xmlns="http://www.mydomain.com/myns" to root element (message) of the XML and it works.