How to generate xml single empty tag for null values while generating xml in JAXB

Biplab :

I am trying to generate xml using JAXB While converting object to xml for null values its coming double empty tag like:

<tag></tag>

But i want this output:

</tag>

I tried

@XmlElement(nillable = true)
private String VoyageID;

But output is coming like this:

<VoyageID xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

I dont want null policy description. Just want this output:

But i tried to remove extra information xmlns:xsi but i am not able to make it work. I tried using package-info.java also but that namespace url coming in above root element of xml.

<VesselDetails>
            <OceanCarrier Code="">
                <Vesselname></Vesselname>
                <VoyageId></VesselVoyageId>
                <PortofEntry></PortofEntry>
            </OceanCarrierSCAC>
<VesselDetails/>

I want output like below:

<VesselDetails>
<OceanCarrier Code=" ">
<Vesselname/>
<VoyageId/>
<PortofEntry/>
</OceanCarrierSCAC>
</VesselDetails>

Madplay :

As you know, <Vesselname/> and <Vesselname></Vesselname> are the same. but if you really want your expected output, I think you need the javax.xml.transform.TransformerFactory.newTransformer()

I did not have your code example so I created it once. Can you test the code below?

final VesselDetails someObj = new VesselDetails();
final JAXBContext context = JAXBContext.newInstance(VesselDetails.class);
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
StringWriter inputWriter = new StringWriter();
marshaller.marshal(someObj, inputWriter);

Source source = new StreamSource(new StringReader(inputWriter.toString()));
Writer resultWriter = new StringWriter();
Result res = new StreamResult(resultWriter);

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.transform(source, res);

System.out.println(resultWriter.toString());

Output:

<VesselDetails>
    <OceanCarrier>
        <Vesselname/>
        <VoyageID/>
        <PortofEntry/>
    </OceanCarrier>
</VesselDetails>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156956&siteId=1