JAXB: How to do mapping between xmlMessage and its Java Class to do unmarshal when we have a lot of type of xmlMessage

Question!

I have XSD file which I have processed using XJC to generate Java classes.

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/Integratipn_Zip" xmlns:tns="http://www.example.org/Integratipn_Zip" elementFormDefault="qualified">

<element name="saveArchiveRequest">
    <complexType>
        <attribute name="identifiant" type="string"></attribute>
        <attribute name="idArchive" type="string"></attribute>
        <attribute name="emplacement" type="anyURI"></attribute>
    </complexType>
</element>

<element name="getArchiveRequest">
    <complexType>
        <attribute name="identifiant" type="string"></attribute>
        <attribute name="idArchive" type="string"></attribute>
    </complexType>
</element>
</schema>

I would like to read XML message, and convert it to one of the generated Java Class. But without using this method:

if (xmlMessage.contains("saveArchiveRequest")){
            JAXBContext jaxbContext = JAXBContext.newInstance(SaveArchiveRequest.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            SaveArchiveRequest object = (SaveArchiveRequest) jaxbUnmarshaller.unmarshal(reader);
            return object;
        } else if (xml.contains("getArchiveRequest")) {
            JAXBContext jaxbContext = JAXBContext.newInstance(GetArchiveRequest.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            GetArchiveRequest object = (GetArchiveRequest) jaxbUnmarshaller.unmarshal(reader);
            return object;
        }

I know that exists method to do this without examining the contents of the XML message, and letting JAXB framework, do mapping directly from the xml message to the right Object, or something like this, maybe using external mapping file.

can someone help me, please ?

Thanks.



Answers

If you create your JAXBContext on the package name that you generated from the XML schema, then you can have a single JAXBContext that is capable of unmarshalling any XML document that corresponds to a global XML in your XML Schema.



This video can help you solving your question :)
By: admin