图片是不言自明的。当我在 CMD 中使用相同的过程验证文档时,该文档被声明为有效。手动检查时有效。
jar 文件生成此消息:
Invalid
schema_reference.4: Failed to read schema document 'E:/XML and Java/Pro XML Development with Java/schema.xsd', 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>.
问题是:为什么?
我正在制作的应用程序需要通过 JAR 文件使用 XSD 验证 XML 的过程。
SSCCE
package xml;
import javax.swing.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.*;
public class JarValidator extends JFrame{
JTextArea area = new JTextArea();
JScrollPane pane = new JScrollPane(area);
SAXParserFactory factory;
SAXParser parser;
final String USER_DIR = System.getProperty("user.dir").replace('\\','/').concat("/");
final String XML_FILE_NAME = "helloWorld.xml";
final String SCHEMA_FILE_NAME = "schema.xsd";
final String JAXP_SCHEMA_LANGUAGE_PROPERTY =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
final String W3_SCHEMA_LANGUAGE = "http://www.w3.org/2001/XMLSchema";
final String JAXP_SCHEMA_SOURCE_PROPERTY = "http://java.sun.com/xml/jaxp/properties/schemaSource";
public JarValidator(){
this.getContentPane().add(pane);
this.pack();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
try{
factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
parser = factory.newSAXParser();
parser.setProperty(JAXP_SCHEMA_LANGUAGE_PROPERTY, W3_SCHEMA_LANGUAGE);
parser.setProperty(JAXP_SCHEMA_SOURCE_PROPERTY,
USER_DIR+SCHEMA_FILE_NAME);
ErrorHandler handler = new ErrorHandler();
parser.parse(new java.io.File(USER_DIR+XML_FILE_NAME), handler);
if(handler.errorOccured == true){
area.append("Invalid \n");
area.append(handler.ex.getMessage());
}else{
area.append("Valid");
}
}catch(SAXException e){
area.append(e.getMessage());
}catch(ParserConfigurationException e){
area.append(e.getMessage());
}catch(java.io.IOException e){
area.append(e.getMessage());
}catch(Exception e){
area.append(e.getMessage());
}
}
private class ErrorHandler extends DefaultHandler{
public SAXParseException ex = null;
public boolean errorOccured = false;
@Override
public void error(SAXParseException ex) {
this.ex = ex;
errorOccured = true;
}
@Override
public void fatalError(SAXParseException ex){
this.ex = ex;
errorOccured = true;
}
@Override
public void warning(SAXParseException ex){
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override public void run(){
new JarValidator();
}
});
}
}
在任何文件夹名称中没有空格的目录结构上,同样的错误。
Invalid
schema_reference.4: Failed to read schema document 'E:/test/schema.xsd', 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>.
只是想我可以补充一下:
我在 Windows 7 32 位机器上。
JAR 与 XML 和 XSD 在同一个文件中,因此user.dir
可以工作。