JAXB unmarshal validation throws cvc-elt.1: Cannot find the declaration of element error

六眼飞鱼酱① 提交于 2019-12-05 06:56:19

This is the fourth hour that I'm trying to find the source of the problem. After much struggle, now, I'm confident that you're missing a single line of code to be able to rise to glorious heights!

The problem is that DocumentBuilderFactory created via DocumentBuilderFactory.newInstance() by default isn't namespace aware—yeah.

You can overcome this in two ways:

  1. make your DocumentBuilderFactory namespace aware:

    DocumentBuilderFactory.setNamespaceAware(true);

  2. or use a StreamSource while unmarshalling and drop the DocumentBuilder and his little friends altogether:

    Unmarshaller.unmarshal(StreamSource, Class<T>);

In case of the second choice you're to do it like this.

InputStream xsdStream = ...
InputStream xmlStream = ...

SchemaFactory f = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema s = schemaFactory.newSchema(xsdStream);

JAXBContext c = JAXBContext.newInstance(CalculateBorrowingDataResponseType.class);
Unmarshaller u = c.createUnmarshaller();
u.setSchema(schema);
CalculateBorrowingDataResponseType b = 
  u.unmarshal(new StreamSource(xmlStream), CalculateBorrowingDataResponseType.class);

By the way, on this schema-awareness-ness-document-builderness-awesomeness there is a lot info in the top section of the Unmarshaller class' documentation, you should definitely check that out!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!