本文介绍了XML 验证不释放 xml 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据 JAVA 中的 XSD 文件验证 XML 文件.我的问题不是验证本身,因为这工作正常.我的问题是,验证后未发布 XML 文件.如果我之后尝试访问该文件,则会收到错误该文件已被另一个资源使用".

I'm trying to validate an XML file against an XSD file in JAVA. My problem is not the validation itself, since this is working fine.My problem is, that the XMLfile is not released after the validation. If I'm trying to access the file afterwards, I get the error "The file is used by another resource".

此错误仅在验证失败时发生(validator.validate(xmlSource); 中抛出异常)如果文件通过验证没有问题,文件就会被释放,其他人可以访问.

This error only happens, when the validation fails (an exception is trown from the validator.validate(xmlSource);)If the file is validated without problems, the file is released and can be accessed by others.

有什么想法吗?

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

推荐答案

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

My suggestion is to create StreamSource using constructor with inputstream.

那样

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

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

and then in your method use finally statement

finally{
inputStream.close();
}

但请记住确保在进入 finally 块之前初始化您的流,或者简单地捕获通过关闭未初始化或打开的 inputStream 引发的异常.

But remember to be sure that you initialize your stream before you go to finally block or simply catch exception thrown by closing not initialized or opened inputStream.

这篇关于XML 验证不释放 xml 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:15