Saxon XML验证:验证失败时无法删除XML文件

时间:2013-08-20 10:54:43

标签: java xml validation saxon well-formed

几个星期前,我在这里发布了issue。现在我有一个类似的问题与不同的情况。我创建了一个java上传,我想检查XML文件是否格式正确。检查后,我想删除它。但如果转换失败,我无法删除该文件。 我创建了一个更简单的示例,在我遇到同样问题的本地计算机上运行它。请参阅下面的源代码。您可以轻松复制并粘贴它并自行尝试。

我是否发现了一个错误,可能是我几周前报告过的错误,或者我是否遗漏了代码中的错误?我使用了Saxon 9.4HE。

public class TestClass 
{
public static void main (String[] args) throws Exception
{
    boolean isWellFormed = isXMLwellformed(new File("work/file.xml"));

    if(isWellFormed) System.out.println("File is well formed");
    else
    {
        System.out.println("File is not well formed");
    }
    FileUtils.deleteDirectory(new File("work"));
}

private static boolean isXMLwellformed(File file)
{
    boolean isWellformed = true;
    TransformerFactory factory = TransformerFactory.newInstance();
    StreamSource source = new StreamSource(file);
    try 
    {
        Transformer trans = factory.newTransformer();
        SAXResult sink = new SAXResult(new DefaultHandler());
        trans.transform(source, sink);
    } 
    catch (TransformerException err) 
    {
        System.err.println("Validation failed: " + err.getMessage());
        isWellformed = false;
    }
    return isWellformed;
}
}

1 个答案:

答案 0 :(得分:1)

现在,我找到了一个有效的解决方案。如果我自己创建FileReader并在catch块中关闭它,它就可以工作。但不应该自动关闭吗?

    private static boolean isXMLwellformed(File file) throws IOException
   {
    boolean isWellformed = true;
    BufferedReader br = new BufferedReader(new FileReader(file));
    TransformerFactory factory = TransformerFactory.newInstance();
    StreamSource source = new StreamSource(br);
    try 
    {
        Transformer trans = factory.newTransformer();
        SAXResult sink = new SAXResult(new DefaultHandler());
        trans.transform(source, sink);
    } 
    catch (TransformerException err) 
    {
        System.err.println("Validation failed: " + err.getMessage());
        br.close();
        isWellformed = false;
    }
    return isWellformed;
    }