XML in Java, how to show an @XmlElement Atribute Java Bean Null as a Empty Valuein XML (Solution Found)

2.7k Views Asked by At

im working in a project. A have a Java Bean with some properties. I mark each attribute with the Tag @XmlElement, like this:

@XmlElement(name="id", nillable = true)
private String test;

I put this "nillable", it shows me the tag, even when is null true but it shows me a message in xml when is null

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

But when it's null i want to show a empty value with the tags only, like this

<id></id>

And i don't know how to do this. I searched but i didn't found how, thats why i'm asking.

And more 1 Thing, can i generate XML that's with no attributes ? Because im My XML i have to generate aloot blank tags, with nothing inside, just the tags and i dont wanna make aloot of atributes if i wont use this just to show the Tag

Thanks !

The imports and some config that i using

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="test")

---------Solution----------

Hi, guys, i found a solution. I Want to share if someone got stuck in same problem. Ou declare the property of the Class as empty, something like String personName = "";

Them you don't need to create the Getters and Setters if you wont change this value and just want the tag appers in XML but empty.

Note: For this work you have to use the @XmlAccessorType(XmlAccessType.FIELD) in your class. Thanks to all. Bye

1

There are 1 best solutions below

0
On BEST ANSWER

There are two ways to represent a null value in XML.

One option is the described xsi:nil. It just adds an empty tag for your attribute and annotates it as holding null value. This form is generated by JAXB if you annotate your attributes with nillable = true.

Note that en empty tag is not the same as a tag with empty string - but more on that later.

Another option is not to represent that attribute at all. There will just be no tag for the attribute in the XML. JAXB uses this approach by default if you don't annotate your Java code with nillable = true but the attributes will still have null values.

And that's it.

Now, to what you want to achieve. Rendering <id></id> basically means that you have an id attribute that holds an empty string. Although you could probably find a language when this is equivalent to null value (Oracle's PL/SQL for instance), it's obviously not an equivalent of null value in Java.

Moreover, if the id is modeled as long or int (or any non-String type) in your Java Bean, the parser will fail to de-serialize such XML back into the bean instance.