问题
Good Morning to everyone!
I am validating an xml against an xsd in this way:
ValidationEventCollector vec;
URL xsdUrl;
Schema schema;
FicheroIntercambio fichero;
vec = new ValidationEventCollector();
try{
xsdUrl = FicheroIntercambio.class.getResource("xsd/file.xsd");
SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
schema = sf.newSchema(xsdUrl);
jaxbContext = JAXBContext.newInstance("file.dto");
unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(schema);
unmarshaller.setEventHandler(vec);
bais = new ByteArrayInputStream(peticion.getBytes("UTF-8"));
fichero = (FicheroIntercambio)unmarshaller.unmarshal(bais);
bais.close();
}catch(Exception ex){
String validacionXml="";
if(vec!=null && vec.hasEvents()){
for(ValidationEvent ve:vec.getEvents()){
validacionXml += ve.getMessage();
}
}else{
validacionXml += ex.getLocalizedMessage();
}
}
part of the xsd is:
<xs:element minOccurs="1" maxOccurs="1" name="Indicador_Prueba">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="1"/>
<xs:enumeration value="0"/>
<xs:enumeration value="1"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
It works perfect, it validates everything. The problem is when it launches this enumeration Exception, it says something like:
cvc-enumeration-valid: Value ''{0}'' is not facet-valid with respect to enumeration ''{1}''. It must be a value from the enumeration
Is it possible to get the element that is throwing the exception? at least get the element type?
thanks in an advance to everyone!
回答1:
Finally, instead of using a ValidationEventCollector which gets the error but in a low level, I used a Validator and to control the errors used an error handler. Now I get the cvc-enumeration-valid error and get which type throwed it. Here is an example:
url = FILE.class.getResource("xsd/file.xsd");
SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
schema = sf.newSchema(xsdUrl);
Validator validator = schema.newValidator();
final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
validator.setErrorHandler(new ErrorHandler() {
public void fatalError(SAXParseException exception) throws SAXException {
// TODO Auto-generated method stub
exceptions.add(exception);
}
public void error(SAXParseException exception) throws SAXException {
// TODO Auto-generated method stub
exceptions.add(exception);
}
});
bais = new ByteArrayInputStream(peticion.getBytes("UTF-8"));
//validate the xml against the xsd
validator.validate(new StreamSource(bais));
if(!exceptions.isEmpty()){
for(SAXParseException ex:exceptions){
validacionXml += ex.getMessage();
}
}
Once you launch the validate method the errorHandler archives all the errors, fatal errors, or warnings if you want getting, in my case, the type that launches the error.
Thanks to everyone
来源:https://stackoverflow.com/questions/34717674/validating-xml-get-the-element-name-that-throws-cvc-enumeration-valid