2

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>

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.