Java - unmarshalling partial XML in XML schema

less than 1 minute read

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class XmlPartialMarshaller<T> {
    private static final Logger LOGGER = LoggerFactory.getLogger(XmlPartialMarshaller.class);
    private DocumentBuilder documentBuilder;
    private DocumentBuilderFactory documentBuilderFactory;
    private Binder<Node> binderPartialXml;
    private JAXBContext contextPartialXml;
    private Class partialSchemaClass;
    public XmlPartialMarshaller(Class<T> partialSchemaClass) {
        this.partialSchemaClass = partialSchemaClass;
        try {
            this.documentBuilderFactory = DocumentBuilderFactory.newInstance();
            this.documentBuilder = documentBuilderFactory.newDocumentBuilder();
            this.contextPartialXml = JAXBContext.newInstance(partialSchemaClass);
            this.binderPartialXml = contextPartialXml.createBinder();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    public T marshalPartialXml(String xml) {
       try {
            InputStream inputStream = null;
            try {
                inputStream = IOUtils.toInputStream(xml);
                Document document = documentBuilder.parse(inputStream);
                Node xmlNode = document.getDocumentElement();
                JAXBElement<T> element = binderPartialXml.unmarshal(xmlNode,
                        partialSchemaClass);
                return element.getValue();
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            } finally {
                if (inputStream != null)
                    inputStream.close();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }
}