Search code examples
javaxmljaxbeclipselinkmarshalling

Unable to marshal xml request with namespace


I am using following code:

JAXBContext jaxbContext = (JAXBContext) JAXBContext.newInstance(AFDType.class);

        AFDType AFDType = new AFDType();
        DeviceInfoType devInfoType = new DeviceInfoType();
        DeviceDetailInfoType devDetailInfoType = new DeviceDetailInfoType();

        devDetailInfoType.setEsnMeidDec("esn1234");
        devInfoType.setBrandCode("brand123");
        devInfoType.setSkuType("sku12345");
        devInfoType.setDeviceDetailInfo(devDetailInfoType);
        AFDType.setDeviceInfo(devInfoType);
        JAXBMarshaller marshaller = jaxbContext.createMarshaller();
        StringWriter sw = new StringWriter();
        marshaller.setProperty(JAXBMarshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(AFDType, sw);

This generates an xml of following format:

<?xml version="1.0" encoding="UTF-8"?>
<ns0:deviceInfo>
   <ns0:deviceDetailInfo>
      <esnMeidDec>esn1234</esnMeidDec>
   </ns0:deviceDetailInfo>
   <ns0:brandCode>brand123</ns0:brandCode>
   <ns0:skuType>sku12345</ns0:skuType>
</ns0:deviceInfo>

However i require following xml:

<ns0:addFD xmlns:ns0="http://ee.abc.com/interfaces/afd/v1/afd.xsd">
         <ns0:deviceInfo>
            <ns0:deviceDetailInfo>
               <ns0:esnMeidHex>36748298746378</ns0:esnMeidHex>
            </ns0:deviceDetailInfo>
            <ns0:brandCode>SPR</ns0:brandCode>
            <ns0:skuType>BYO</ns0:skuType>
         </ns0:deviceInfo>
      </ns0:addFD>

Can someone please help me how to obtain the 2nd xml.


Solution

  • Add package-info.java into interfaces.afd root folder with the following content

    @XmlSchema(
        elementFormDefault=XmlNsForm.QUALIFIED,
        namespace="http://ee.abc.com/interfaces/afd/v1",
        xmlns={@XmlNs(prefix="ns0",
                      namespaceURI="http://ee.abc.com/interfaces/afd/v1")}
    )
    package interfaces.afd;
    
    import javax.xml.bind.annotation.XmlNs;
    import javax.xml.bind.annotation.XmlNsForm;
    import javax.xml.bind.annotation.XmlSchema;
    

    Read more about it here.

    The enclosing root element <ns0:addFd></ns0:addFd> can be achieved by adding @XmlRootElement(name = "addFd") tag above the AddFd.class like below :

    @XmlRootElement(name = "addFd")
    public class AddFd {
    ..
    }