使用DOM解析器进行XML解析
问题描述:
在我的应用程序中,我试图使用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;
}
}
答
我刚刚发现一个笑着的方式..
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;
}
您需要捕获异常,并在发现你需要移动XML错误的文件夹。更新有问题的代码。 – vels4j
您还没有指定任何语言或特定的技术,因此我们所能做的只是猜测。在特殊情况下,很可能没有及时清理某些东西。例如,如果您的语言支持它们,则可以通过明智地使用'finally'块或'using'子句来解决这个问题。 –
hi vels4j,我用代码更新了这个问题。感谢 –