在JAXB中,我可以创建一个Unmarshaller实例并使用它来多次解组xml节点或文件吗?

时间:2013-03-21 08:41:28

标签: java xml jaxb sax

我使用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);
        }
    ...

1 个答案:

答案 0 :(得分:6)

只要您的JAXBContext没有更改,您就可以重用unmarshaller。

另见Javadoc for JAXBContext。它包含一个为多个XML文件重用相同的unmarshaller的示例,仅当上下文(BazObject的包不在上下文路径上)发生更改时,您需要从不同的上下文创建一个新的unmarshaller。