我使用SAX来解析一个大的xml文件,它有很多重复的节点.并使用JAXB将已解析和重复的dom节点映射到javabeans以实现持久性.
这是我的代码片段.我使用JAXB的partial unmarshalling示例代码,每次启动节点解析时都会创建Unmarshaller对象.我可以将它重用于一个完整的xml解析或缓存它以进行多个xml解析吗?
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
...
if (namespaceURI.equals("") && localName.equals( “product” )) {
Unmarshaller unmarshaller = null;
try {
//I want to reuse it, not create it in each startElement method
unmarshaller = jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
throw new SAXException(e);
}
...
Run Code Online (Sandbox Code Playgroud)
只要您的JAXBContext没有更改,您就可以重用unmarshaller.
另请参阅JAXBContext的Javadoc.它包含一个为多个XML文件重用相同的unmarshaller的示例,仅当上下文(BazObject不在上下文路径中的包)发生更改时,您需要从不同的上下文创建新的unmarshaller.