我想验证一个XML文件在JAVA中的XSD文件。我的问题不是验证本身,因为这工作正常。 我的问题是,验证后XML文件未发布。如果之后尝试访问该文件,则会出现错误“该文件被其他资源使用”。XML验证不会释放xml文件
只有在验证失败时才会发生此错误(从validator.validate(xmlSource); troll发出异常;) 如果该文件没有问题进行验证,则该文件被释放并且可被其他人访问。
任何想法?
public void validateXMLAgainstXSD(String xmlPath, String xsdPath) throws ParserException, IOException
{
Source xmlSource = null;
File schemaFile = null;
SchemaFactory schemaFactory = null;
Schema schema = null;
Validator validator = null;
try
{
schemaFile = new File(xsdPath);
xmlSource = new StreamSource(new File(xmlPath));
schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schema = schemaFactory.newSchema(schemaFile);
validator = schema.newValidator();
validator.validate(xmlSource);
}
catch (SAXException e)
{
//_log.error("ParsingDataFile: XML file could not be validated against XSD file: XML File=<", xmlFile.getAbsolutePath(), "> XSD file=<", xsdFile.getAbsolutePath(), ">. Exception=<", e, ">");
xmlSource = null;
schemaFile = null;
schemaFactory = null;
schema = null;
validator.reset();
validator = null;
//throw new ParserException(-1, ParserException.ERROR_CODE_XML_NOT_VALID, e);
}
}
你是如何'试图访问文件'? – 2014-02-21 10:48:22
您总是必须关闭已打开的资源或大部分时间。我没有看到你使用任何'finally'块。 – Omoro
@LutzHorn我尝试将文件从一个目录移动到另一个目录。但Rafik991提供的解决方案解决了我的问题。 –