Using SAX with JAXBContext

*爱你&永不变心* 提交于 2019-12-04 18:32:46

You could try the following approach using JAXB's UnmarshallerHandler:

package forum10890323;

import java.io.InputStream;
import javax.xml.bind.*;
import javax.xml.parsers.*;
import org.xml.sax.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);
        UnmarshallerHandler unmarshallerHandler = jc.createUnmarshaller().getUnmarshallerHandler();

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(unmarshallerHandler);

        InputStream inputStream = Root.class.getClassLoader().getResourceAsStream("forum10890323/input.xml");
        InputSource inputSource = new InputSource(inputStream);
        xr.parse(inputSource);
        inputStream.close();

        Root root = (Root) unmarshallerHandler.getResult();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!