使用DOM解析器进行XML解析

时间:2013-07-19 08:14:51

标签: java xml-parsing

在我的应用程序中,我尝试使用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;
}

}

1 个答案:

答案 0 :(得分: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;
}