2013-07-19 121 views
0

在我的應用程序中,我試圖使用DOM解析器解析XML文件。如果解析成功,那麼該文件將被移動到成功目錄,否則將出現錯誤directory.next從源目錄中刪除文件使用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; 
} 

}

+0

您需要捕獲異常,並在發現你需要移動XML錯誤的文件夾。更新有問題的代碼。 – vels4j

+0

您還沒有指定任何語言或特定的技術,因此我們所能做的只是猜測。在特殊情況下,很可能沒有及時清理某些東西。例如,如果您的語言支持它們,則可以通過明智地使用'finally'塊或'using'子句來解決這個問題。 –

+0

hi vels4j,我用代碼更新了這個問題。感謝 –

回答

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