Using XmlAdapter to generate desired xml format

Download java eBook


When desired XML format differs from Java object model, an XmlAdapter implementation can be used to transform model object into xml-format object and vice versa. This example demonstrates how to put a field's value into an attribute of an element with field's name.

public class XmlAdapterExample {

    public static class NodeValueElement {
        String value;
        public NodeValueElement() {
        public NodeValueElement(String value) {
            this.value = value;
        public String getValue() {
            return value;
        public void setValue(String value) {
            this.value = value;

    public static class ValueAsAttrXmlAdapter extends XmlAdapter<NodeValueElement, String> {        
        public NodeValueElement marshal(String v) throws Exception {
            return new NodeValueElement(v);
        public String unmarshal(NodeValueElement v) throws Exception {
            if (v==null) return "";
            return v.getValue();

    public static class DataObject {
        String elementWithValue;

        String elementWithAttribute;

    public static void main(String[] args) {
        DataObject data = new DataObject();
        data.elementWithAttribute ="value2";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JAXB.marshal(data, baos);

        String xmlString = new String(baos.toByteArray(), StandardCharsets.UTF_8);


Contributors: 1
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook