so right now when I validate the XML file using an XML schema, I am only able to know whether it fail or pass, and if I want to know why it fail, I need to look at the error message like
[org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'City'. One of '{Address1}' is expected.]
In the above example, it fail because I am missing tag Address1
. My question is When the validation fail, can I know which tag causing the failure? This is because I need to handle these failure differently for each important missing-tag. Right now my thought is
FileInputStream inputStream = null;
try{
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File(config.getXmlSchema()));
JAXBContext context = JAXBContext.newInstance(PackageLabel.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setSchema(schema);
inputStream = new FileInputStream(xmlFile);
pl = (PackageLabel) unmarshaller.unmarshal(inputStream);
} catch (JAXBException e) {
if(pl.getAddress1() == null){
System.out.println("Invalid Mailing Address");
}
//EDIT: CANNOT DO THIS, SINCE pl IS NULL AT THIS POINT
//Some more logics on how to handle important missing-tags
...
}finally{
if(inputStream != null) inputStream.close();
}
However, I do not think writing logic inside catch clause
is correct. Any advice?
EDIT
I followed Balaise idea, and below is the event I received when the XML missing an Address1
EVENT
SEVERITY: 2
MESSAGE: cvc-complex-type.2.4.a: Invalid content was found starting with element 'City'. One of '{Address1}' is expected.
LINKED EXCEPTION: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'City'. One of '{Address1}' is expected.
LOCATOR
LINE NUMBER: 4
COLUMN NUMBER: 11
OFFSET: -1
OBJECT: null
NODE: null
URL: null
However, both NODE
and OBJECT
are null, I cannot further investigate on what causing the exception unless I parse the exception which is what I asked originally.