编程生活

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  113 随笔 :: 0 文章 :: 18 评论 :: 0 Trackbacks

 

最近在使用javax.xml.parsers.DocumentBuilder解析xml文件的时候偶尔会出错:

 

org.xml.sax.SAXException: FWK005 parse may not be called while parsing.
        at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:
263)
        at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:
284)
        at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:
208)

 

跟踪了一下代码,发现这个异常是在com.sun.org.apache.xerces.internal.parsers.DTDConfiguration.parse(DTDConfiguration.java:546)抛出来的。该段代码结构如下:

 

if(fParseInProgress) {
    
throw new XNIException("FWK005 parse may not be called while parsing.");
}


fParseInProgress 
= true;

// 解析xml文件

finally {
    fParseInProgress 
= false;
}

 

从程序逻辑来看,如果当前DocumentBuilder对象正在转换文档,此时再次请求转换文档,那么直接抛出XNIException(“FWK005 parse may not be called while parsing.”);异常。

这个问题也比较好解决,一种是对转换xml文档的方法,增加synchronized关键字,这样子不会有两个线程同时访问方法。

还有一种方法是创建一个DocumentBuilder类型的ThreadLocal变量,这样子每个线程都拥有自己的DocumentBuilder对象,能够同时转换多个xml文件。代码如下:

 

private static ThreadLocal docBuildeIns = new ThreadLocal() {
    
protected DocumentBuilder initialValue() {
        
try {
            
return DocumentBuilderFactory.newInstance().newDocumentBuilder();
        }
 catch (ParserConfigurationException e) {
            String msg 
= "DocumentBuilder 对象初始化失败!";
            log.error(msg, e);
            
throw new IllegalStateException(msg, e);
        }

    }

}
;

 

posted on 2012-05-09 17:18 wilesun 阅读(6374) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: