作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试根据 Java 中的模式验证 XML 文件,问题是如果文件验证失败,则文件将被锁定,直到应用程序终止。如果输入文件有效,则文件不会被锁定,一切都很好。
我正在使用 javax.xml.validation.Validator
和 validate()
方法。这看起来很简单,并且在验证通过时就可以了。我只能假设我在错误处理中遗漏了一些东西,但是 Validator 的 API 似乎没有提供任何有用的东西。谁能阐明我在这里做错了什么?
我已将所有这些简化为下面的一个独立类。如果您运行它,那么在扫描程序启动时,检查输入文件,您可以看到它现在已被锁定。如果您需要,我可以提供输入和结构文件。
谢谢,
菲尔
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.URI;
import java.util.Scanner;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
public class ValidationTest {
public static void validate(URI xmlLocation, URI schemaLocation) throws Exception {
SchemaFactory schemaFactory = SchemaFactory.newInstance( "http://www.w3.org/2001/XMLSchema" );
Source schemaSource = new StreamSource(schemaLocation.toString());
Schema schema = schemaFactory.newSchema(schemaSource);
Validator schemaValidator = schema.newValidator();
StreamSource source = new StreamSource(xmlLocation.getPath());
schemaValidator.validate( source );
}
public static void main(String[] args) throws Exception {
File srcFile = new File("c:/aaa/MySrc-Broken.xml");
File schema = new File("c:/aaa/MyStructureDefinition.xsd");
try {
ValidationTest.validate(srcFile.toURI(), schema.toURI());
} catch(Exception e) {
System.err.println(e);
}
// Use a Scanner to pause the thread, so that I can
// go and check the file's permissions.
Scanner scan = new Scanner(System.in);
scan.nextLine();
}
}
更新:
我有一点技巧,它提供了一个(糟糕的)解决方案。我将自定义 errorHandler 添加到 schemaValidator。这个 errorHandler 只是将任何错误存储在一个成员变量中。这意味着 validator 将始终成功,从而释放对输入文件的所有锁定。但是,我必须检查错误处理程序以查看是否有任何错误,如果有则抛出错误。这不是很好,但确实让我解决了这个问题。
最佳答案
请注意,不允许使用 StreamSource 实例。( http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/validation/Validator.html )
URL xmlFileURL = xmlFileToCheck.toURI().toURL();
InputStream inputStream = xmlFileURL.openStream();
InputSource is = new InputSource(inputStream);
SAXSource saxSource = new SAXSource(is);
xmlValidator.validate(saxSource);
inputStream.close(); // this is probably important...
关于Java Validator 在失败时锁定文件——我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8170294/
我是一名优秀的程序员,十分优秀!