Want to get all Errors List when I validate XML using JAXB

jaxb

Can you please help me to get the list of all errors when I validate the XML file using JAXB?

Right now I have already implemented the code for the same. I have implemented the code using unmarshalling the XML file.

When I unmarshalling the XML file at that time if any error would be there in the XML file, I got the exception but it came out after giving the first exception but I want the list of all errors of that XML file. This should not come out after getting the first error.

Source xsdFileName = new StreamSource(new File("validate6.xsd"));
    Source xmlFileName = new StreamSource(new File("test3.xml"));

    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(xsdFileName);

        JAXBContext jc = JAXBContext.newInstance(Innovations.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new MyValidationEventHandler());
        Innovations innovation = (Innovations) unmarshaller.unmarshal(xmlFileName);

        System.out.println("Total Size :: " + innovation.getInnovationList().size());
        System.out.println(xmlFileName.getSystemId() + " is valid");
    } catch (JAXBException e) {
        e.printStackTrace();
        System.out.println(xmlFileName.getSystemId() + " is NOT valid");
    } catch (SAXParseException e) {
        e.printStackTrace();
        System.out.println(xmlFileName.getSystemId() + " is NOT valid");
    } catch (SAXException e) {
        e.printStackTrace();
        System.out.println(xmlFileName.getSystemId() + " is NOT valid");
    }

XSD File:

<xs:schema attributeFormDefault="unqualified"
elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="innovations">
    <xs:complexType>
        <xs:sequence>
            <xs:element type="xs:string" name="organization" />
            <xs:element name="innovation" maxOccurs="unbounded"
                minOccurs="1">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="title" minOccurs="1">
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:minLength value="1" />
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:element>
                        <xs:element name="brief_description" minOccurs="1">
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:minLength value="1" />
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:element>
                        <xs:element name="categories" minOccurs="1">
                            <xs:complexType mixed="true">
                                <xs:sequence>
                                    <xs:element name="category" maxOccurs="unbounded"
                                        minOccurs="1">
                                        <xs:simpleType>
                                            <xs:restriction base="xs:string">
                                                <xs:minLength value="1" />
                                            </xs:restriction>
                                        </xs:simpleType>
                                    </xs:element>
                                </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                        <xs:element name="tags" minOccurs="1">
                            <xs:complexType>
                                <xs:sequence>
                                    <xs:element name="tag" maxOccurs="unbounded"
                                        minOccurs="1">
                                        <xs:simpleType>
                                            <xs:restriction base="xs:string">
                                                <xs:minLength value="1" />
                                            </xs:restriction>
                                        </xs:simpleType>
                                    </xs:element>
                                </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                        <xs:element name="full_description" minOccurs="1">
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:minLength value="1" />
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:element>
                        <xs:element name="patent_number" maxOccurs="unbounded" minOccurs="0">
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:minLength value="1" />
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:element>
                        <xs:element name="patent_status" maxOccurs="unbounded" minOccurs="0">
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:minLength value="1" />
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:element>
                        <xs:element name="case_manager" minOccurs="1">
                            <xs:complexType>
                                <xs:simpleContent>
                                    <xs:extension base="xs:string">
                                        <xs:attribute type="xs:string" name="first_name"
                                            use="optional" />
                                        <xs:attribute type="xs:string" name="last_name"
                                            use="optional" />
                                    </xs:extension>
                                </xs:simpleContent>
                            </xs:complexType>
                        </xs:element>
                        <xs:element name="status" minOccurs="1">
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:minLength value="1" />
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:element>
                    </xs:sequence>
                    <xs:attribute type="xs:short" name="file_number" use="required" />
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

Validation Event Handler Class

public class MyValidationEventHandler implements ValidationEventHandler {

public boolean handleEvent(ValidationEvent event) {
    System.out.println("\nEVENT");
    switch (event.getSeverity()) {
    case 0:
        System.out.println("SEVERITY:  WARNING");
        break;
    case 1:
        System.out.println("SEVERITY:  ERROR");
        break;
    case 2:
        System.out.println("SEVERITY:  FATAL_ERROR");
        break;
    }
    System.out.println("MESSAGE:  " + event.getMessage());
    System.out.println("LINKED EXCEPTION:  " + event.getLinkedException());
    System.out.println("LOCATOR");
    System.out.println("    LINE NUMBER:  " + event.getLocator().getLineNumber());
    System.out.println("    COLUMN NUMBER:  " + event.getLocator().getColumnNumber());
    System.out.println("    OFFSET:  " + event.getLocator().getOffset());
    System.out.println("    OBJECT:  " + event.getLocator().getObject());
    System.out.println("    NODE:  " + event.getLocator().getNode());
    System.out.println("    URL:  " + event.getLocator().getURL());
    return true;
}

}

Output:

EVENT
SEVERITY: FATAL_ERROR
MESSAGE: cvc-complex-type.2.4.a: Invalid content was found starting with element 'case_manager1'. One of '{patent_status, case_manager}' is expected.
LINKED EXCEPTION: org.xml.sax.SAXParseException; systemId: file:/D:/AHWeb2.0.3/test3.xml; lineNumber: 24; columnNumber: 55; cvc-complex-type.2.4.a: Invalid content was found starting with element 'case_manager1'. One of '{patent_status, case_manager}' is expected.
LOCATOR
LINE NUMBER: 24
COLUMN NUMBER: 55
OFFSET: -1
OBJECT: null
NODE: null
URL: file:/D:/AHWeb2.0.3/test3.xml

EVENT
SEVERITY: ERROR
MESSAGE: unexpected element (uri:"", local:"case_manager1"). Expected elements are <{}tags>,<{}title>,<{}patent_number>,<{}brief_description>,<{}status>,<{}full_description>,<{}categories>,<{}case_manager>,<{}patent_status>
LINKED EXCEPTION: null
LOCATOR
LINE NUMBER: 24
COLUMN NUMBER: 55
OFFSET: -1
OBJECT: null
NODE: null
URL: file:/D:/AHWeb2.0.3/test3.xml

EVENT
SEVERITY: FATAL_ERROR
MESSAGE: The element type "case_manager1" must be terminated by the matching end-tag "".
LINKED EXCEPTION: org.xml.sax.SAXParseException; systemId: file:/D:/AHWeb2.0.3/test3.xml; lineNumber: 25; columnNumber: 5; The element type "case_manager1" must be terminated by the matching end-tag "".
LOCATOR
LINE NUMBER: 25
COLUMN NUMBER: 5
OFFSET: -1
OBJECT: null
NODE: null
URL: file:/D:/AHWeb2.0.3/test3.xml
file:/D:/AHWeb2.0.3/test3.xml is NOT valid
javax.xml.bind.UnmarshalException
– with linked exception:
[org.xml.sax.SAXParseException; systemId: file:/D:/AHWeb2.0.3/test3.xml; lineNumber: 25; columnNumber: 5; The element type "case_manager1" must be terminated by the matching end-tag "".]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(Unknown Source)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:514)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:215)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:184)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
at com.test.innovation.validation.InnovationUnmarshalDemo.main(InnovationUnmarshalDemo.java:34)
Caused by: org.xml.sax.SAXParseException; systemId: file:/D:/AHWeb2.0.3/test3.xml; lineNumber: 25; columnNumber: 5; The element type "case_manager1" must be terminated by the matching end-tag "".
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:211)
… 4 more

Thanks.

Best Answer

I guess a custom validator will help you:

public class MyValidationEventHandler implements ValidationEventHandler{

    public boolean handleEvent(ValidationEvent ve) {            
        if (ve.getSeverity()==ve.FATAL_ERROR ||  
                ve .getSeverity()==ve.ERROR){
            ValidationEventLocator  locator = ve.getLocator();
            //print message from valdation event
            System.out.println("Message is " + ve.getMessage());
            //output line and column number
            System.out.println("Column is " + 
                    locator.getColumnNumber() + 
                    " at line number " + locator.getLineNumber());
        }
        return true;
    }

}

and then

setEventHandler(new MyValidationEventHandler()); 
Related Topic