XML验证不会释放xml文件

时间:2014-02-21 10:38:29

标签: java xml validation

我正在尝试针对JAVA中的XSD文件验证XML文件。我的问题不是验证本身,因为这工作正常。 我的问题是,验证后没有发布XML文件。如果我之后尝试访问该文件,则会收到错误“该文件被其他资源使用”。

此错误仅在验证失败时发生(从validator.validate(xmlSource)中输出异常;) 如果文件经过验证而没有问题,则该文件将被释放并可供其他人访问。

任何想法?

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);
    }
  }

2 个答案:

答案 0 :(得分:1)

我的建议是使用带有inputstream的构造函数创建StreamSource。

像那样

 InputStream inputStream = new FileInputStream(new File(xmlPath));
    source = new StreamSource(inputStream);

然后在你的方法中使用finally语句

finally{
inputStream.close();
}

但是请记住确保在转到finally块之前初始化流,或者只是通过关闭未初始化或打开的inputStream来捕获异常。

答案 1 :(得分:0)

RMachnik是正确的,就像一个魅力!

还可以使用TryWithResources

try (InputStream inputStream = new FileInputStream(file)) {
    ...
    new StreamSource(inputStream);
    ...
}