[英]How to validate a xml file against a given xsd file while parsing it with a sax parser?
[英]SAX Praser Exception while parsing a XML against an XSD in a standalone java application
我开发了一个独立的Java工具,可以针对xsd验证XML文件以检查格式错误。 格式检查工作正常,但我必须对xml文件中的数据添加一些验证。 我编写了以下代码来解析和验证文件格式。 我发现如果存在任何格式错误,它将与我的自定义错误消息一起正确显示。 但是一个好的文件并不能创建我要检查数据验证的文档。 而且我收到如下错误。
final String ENCODING = "UTF-8";
final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
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());
打印时doc的值将为空。 我在日志中得到的异常如下。
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)
请提出我在做什么错。
谢谢Nirmalya
我找出了异常的原因。 我正在尝试的是导入保存了XSD文件(com.fileReader.properties)的包,并尝试在另一个包(com.fileReader.reader)的java类中解析它。 现在,当我将XSD与Java文件(com.fileReader.reader)放在同一包中时,将对其进行处理而没有任何异常。 我不知道为什么导入软件包不起作用。 谁能给我一个为什么不能导入软件包的想法。 谢谢Nirmalya
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.