Search code examples
jaxbjaxb2

Unqualified Element with Qualified Type Reference


I am essentially trying to produce the following chunk of XML from JAXB Annotations.

<pCredentials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:type="ns3:LoginCredentials">
        <loginId>user</loginId>
        <loginPassword>password</loginPassword>
        <userType>super</userType>
     </pCredentials>

I tried the following annotations and multiple variations of the same type:

@XmlElement(name = "pCredentials", namespace = "##default", type = com.foo.LoginCredentials.class)
private LoginCredentials pCredentials;

But it produces the following:

   <pCredentials>
        <loginId>user</loginId>
        <loginPassword>password</loginPassword>
        <userType>super</userType>
     </pCredentials>

Any suggestions as to what type of annotations I can provide that will produce the type reference?

Thanks for the help...Jay


Solution

  • You JAXB implementation will only add an xsi:type attribute when the Java type of the value does not match the expected type of the element. This is why what you tried will not work (since you are saying the elements type is the same type as the value.

    You could do the following:

    @XmlElement(type = Object.class)
    private LoginCredentials pCredentials;
    

    Note

    • The xsi:type attribute will be required in the XML being unmarshalled.
    • You will need to include LoginCredentials in the list of classes given to bootstrap the JAXBContext.

    For More Information