Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

JAXB by default would output the value of a getter for property “oldName” as data. Specify @XmlElement if you want to use a different name.

@XmlElement(name ="newName")
public String getOldName() {
     return oldName;
}

Thanks to @XmlElement, it will be outputted as data.

This is especially useful when you have a list of objects. Normally you would have something like:

public List<String> getValues() {
     return values;
}

You would need a way to get the collection of data. This can be accomplished by adding @XmlElementWrapper.

@XmlElementWrapper(name = "valueList")
public List<String> getValues() {
     return values;
}

This would create the following output

<valueList>
     <values>value</values>
     <values>value</values>
     <values>value</values>
     <values>value</values>
</valueList>

This is correct, but I don’t like to have a plural name for a single value container. I could change the name of my property to be value, but that looks weird when I iterate over value in my code. A better solution is to specify a wrapper and an element.

@XmlElementWrapper(name = "valueList")
@XmlElement(name = "value")
public List<String> getValues() {
     return values;
}

This would create the following output

<valueList>
     <value>value</value>
     <value>value</value>
     <value>value</value>
     <value>value</value>
</valueList>

Everybody is happy. My code looks like it should and the xml looks like it should.

August 21st, 2012

Posted In: Java, JAXB, xml

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By : XYZScripts.com