Search code examples
jaxbeclipselinkmoxyunmarshalling

unmarshal to different object using MOXy


I have a response xml with root element SearchResourceResponse. I need to unmarshal that into a different custom(HSIDetails) object.I started using MOXy as my JAXB (JSR-222) implementation. is my below intension correct?? is this possible with MOXy ??

JAXBContext jc = JAXBContext.newInstance(HSIDetails.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
HSIDetails hsiDetails = (HSIDetails) unmarshaller.unmarshal(new StreamSource(new StringReader(responseXml)));

and my HSIDetails class

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class HSIDetails implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = -4352912510533245455L;

    @XmlPath("SearchResponseDetails/LogicalDevice/LogicalPhysicalResource/PhysicalResource[@*[local-name()='type' and contains(.,'icl:Slot')]]/commonName")
    private String slot;
    @XmlPath("SearchResponseDetails/LogicalDevice/LogicalPhysicalResource/PhysicalResource[@*[local-name()='type' and contains(.,'icl:PhysicalPort')]]/commonName")
    private String port;

    @XmlPath("SearchResponseDetails/SubNetwork/Pipe/commonName")
    private String telephone;

    @XmlPath("//SearchResponseDetails/SubNetwork/Pipe/lrStatus")
    private String lrStatus;

    public String getSlot() {
        return slot;
    }
    public void setSlot(String slot) {
        this.slot = slot;
    }
    public String getPort() {
        return port;
    }
    public void setPort(String port) {
        this.port = port;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getLrStatus() {
        return lrStatus;
    }
    public void setLrStatus(String lrStatus) {
        this.lrStatus = lrStatus;
    }
}

and part of my xml is:

<tns:SearchResourceResponse xmlns:tns="http://www.ICLNBI.com/ICLNBI.xsd">
    <SearchResponseDetails>
        <SubNetwork>
            <Pipe xsi:type="icl:Trail" xmlns:icl="http://www.ICLNBI.com/ICLNBI.xsd"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <CommonName>XXXXX</CommonName>
                <objectID>1234567890</objectID>
                <description>512/2</description>
                <SourceSystem>YYYY</SourceSystem>
            </Pipe>
        </SubNetwork>
    </SearchResponseDetails>
</tns:SearchResourceResponse>

Solution

  • You can use one of the unmarshal methods that take a Class parameter to tell MOXy or any JAXB (JSR-222) implementation what class to unmarshal to.

     JAXBContext jc = JAXBContext.newInstance(HSIDetails.class);
     Unmarshaller unmarshaller = jc.createUnmarshaller();
     HSIDetails hsiDetails = unmarshaller.unmarshal(
         new StreamSource(new StringReader(responseXml)), 
         HSIDetails.class).getValue();