0

在我的应用程序中,我正在尝试使用 DOM 解析器解析 XML 文件。如果解析成功,则将文件移动到成功目录,否则移动到错误目录。接下来,文件将从源目录中删除

问题是,当某些格式不正确的 XML 文件(例如:Xml 文档缺少结束标记)时,会抛出异常以及以下错误消息。

"该进程无法访问该文件,因为它正被另一个进程使用。 "

因此,该文件不会从源目录中删除。

public  class XMLLoader extends Thread {
boolean success =false;
public XMLLoader(SoapConnection con, String xmlPath) {

    try {
        System.out.println("Laoding the XML...");
        File file = new File(xmlPath);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(file);
        String xmlString = null;

        DOMSource domSource = new DOMSource(document);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        xmlString = writer.toString();
        InboundCaseXmlResponse cResponse = con.LoadXmlCase(xmlString);
        System.out.println("SOAP Response == "+cResponse);
        if(cResponse.getHasErrors()== false)
        {
            success = true; 
        }


    } catch (Exception e) {
        System.out.println(e.getMessage());

        }


}
public boolean getStatus()
{
    return success;
}

}

4

1 回答 1

0

我刚刚找到了一个简单的方法..

private static boolean loadXml(SoapConnection con, String xmlPath) {
    boolean success =false;
    FileInputStream file=null;
    try {
        System.out.println("Loading the XML...");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        file = new FileInputStream(xmlPath);
        Document document = builder.parse(file);
        System.out.println(document.hasChildNodes());
        String xmlString = null;            
        DOMSource domSource = new DOMSource(document);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        xmlString = writer.toString();
        InboundCaseXmlResponse cResponse = con.LoadXmlCase(xmlString);
        System.out.println("SOAP Response == "+cResponse);
        if(cResponse.getHasErrors()== false)
        {
            success = true; 
        }
        } catch (Exception e) {
        System.out.println(e.getMessage());
        try{
        file.close();
        }
        catch(Exception ex)
        {
        e.printStackTrace();    
        }

        }

    return success;
}
于 2013-07-22T11:20:05.780 回答