I have a xml file and I want to convert it into a java object using JAXB. I am getting an exception related to validation. It seems JAXB is validating it against the DTD which is declared in the xml file. Unfortunately the DTD is not at the location which is mentioned in the xml file. So I kept a local copy and used an EntityResolver to make JAXB use the local DTD. And the code worked like a charm.
Below is the code
JAXBContext context = JAXBContext.newInstance(Student.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
final XMLReader reader = saxParserFactory.newSAXParser().getXMLReader();
reader.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(final String publicId, final String systemId) throws SAXException, IOException {
return new InputSource(getClass().getResourceAsStream("/student.dtd"));
}
});
final SAXSource saxSource = new SAXSource(reader, new InputSource(inputStream));
student = (Student) unmarshaller.unmarshal(saxSource);
This code is inside my method parse(xmlFilePath). Every time I call parse method a new EntityResolver is created. Is this not redundant? Can I create one EntityResolver in the class's constructor and pass it to the setEntityResolver method?
public StudentParser() {
this.entityResolver = new EntityResolver() {
@Override
public InputSource resolveEntity(final String publicId, final String systemId) throws SAXException, IOException {
return new InputSource(getClass().getResourceAsStream("/student.dtd"));
}
}
}
Inside parse method
public Student parse(filePath) {
...
...
reader.setEntityResolver(this.entityResolver);
...
}