Add schema location to JAXB unmarshaller

2019-08-22 04:51发布

问题:

I am facing the below error when JABX unmarshaller tries to unmarshall the xml

Exception in thread "main" javax.xml.bind.UnmarshalException - with linked exception: [org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 456; The prefix "xsi" for attribute "xsi:nil" associated with an element type "customerProductStatus" is not bound.]

When I looked at the xml being returned from the server , it is the below :

<customerProductStatus xsi:nil = "true"></customerProductStatus>

I don't see xsi defined in any of the parent tags. Is it possible to add the schemaLocation to unmarshaller without changing any of the bindings?

JAXBContext jaxbContext1 = JAXBContext.newInstance(Request.class);
Unmarshaller jaxbUnMarshaller1 = jaxbContext1.createUnmarshaller();
Request request = (Request)jaxbUnMarshaller1.unmarshal(receiveData.getBinaryStream());

回答1:

You can add this:

//Gets schema
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xmlSchema);

JAXBContext jaxbContext1= JAXBContext.newInstance(Request.class);
Unmarshaller jaxbUnMarshaller1 = jaxbContext1.createUnmarshaller();

//Sets schema with unmarshaller
jaxbUnMarshaller1 .setSchema(schema);

Request request = (Request)jaxbUnMarshaller1.unmarshal(receiveData.getBinaryStream());

The required packages are:

import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;