I developed a standalone java tool to validate a XML file against a xsd to check for format errors. Format checking is working fine but I have to add few validation on the data in the xml file. I wrote the below code for parsing and validating the format of the file. I found that if any format error exists it is displayed properly with my custom error messages. But a good file is not creating the document where I would check for data validation. And i am getting an error like below.
final String ENCODING = "UTF-8";
final String JAXP_SCHEMA_LANGUAGE = "http://ift.tt/1eGAWXh";
final String W3C_XML_SCHEMA = "http://ift.tt/tphNwY";
final String JAXP_SCHEMA_SOURCE = "http://ift.tt/1B7QTyM";
boolean validateFlag = false;
System.out.println("Preparing XSD File .......");
//File fSchemaFile = new File("D:\\Workspaces\\Tools Workspace\\FileReader\\FileReader\\src\\com\\fileReader\\main\\PIF_BPX_FORMAT.XSD");
InputSource schemaFile = new InputSource(getClass().getResourceAsStream("PIF_BPX_FORMAT.XSD"));
System.out.println("SchemaFile : " +schemaFile.toString());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
System.out.println("XMLVALIDATOR - DOCUMENT BUILDER FACTORY CREATED -" + dbf.toString());
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
dbf.setAttribute(JAXP_SCHEMA_SOURCE, schemaFile);
System.out.println("XMLVALIDATOR - SCHEMA CONFIGURED ");
// Parse an XML document into a DOM tree.
DocumentBuilder db = dbf.newDocumentBuilder();
OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, ENCODING);
System.out.println("ErrorWriter : "+errorWriter.toString());
db.setErrorHandler(new BPXFormatErrorHandler(new PrintWriter(errorWriter, true)));
System.out.println("After Error Handler");
Document doc = db.parse(file);
System.out.println("XMLVALIDATOR - XML PARSED" + doc.toString());
The value of doc when printed is coming null. The exception that I am getting in the logs is as below.
Preparing XSD File .......
SchemaFile : org.xml.sax.InputSource@1172aa6
XMLVALIDATOR - DOCUMENT BUILDER FACTORY CREATED -com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl@1ffd111
XMLVALIDATOR - SCHEMA CONFIGURED
ErrorWriter : java.io.OutputStreamWriter@57df88
Inside BPXFormatErrorHandler constructor
After Error Handler
Inside getParseExceptionInfo method
org.xml.sax.SAXParseException; systemId: file:/D:/My%20Projects/Java/Eclipse%20Related/GoodFile.xml; lineNumber: 1; columnNumber: 7; schema_reference.4: Failed to read schema document 'null', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
Please suggest what I am doing wrong.
Thanks Nirmalya
No comments:
Post a Comment