Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

public class Main {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Messages.class);

        Messages messages = new Messages();
        messages.getMessages().add(new Message());
        messages.getMessages().add(new Message());
        messages.getMessages().add(new Message());

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setAdapter(new IDAdapter());
        marshaller.marshal(messages, System.out);
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    public static class Message {

        @XmlAttribute
        @XmlJavaTypeAdapter(IDAdapter.class)
        private Integer id = 0;

    }

    public static class IDAdapter extends XmlAdapter<Integer, Integer> {

        private int counter = 1;

        @Override
        public Integer unmarshal(Integer v) throws Exception {
            return v;
        }

        @Override
        public Integer marshal(Integer v) throws Exception {
            return counter++;
        }

    }

    @XmlRootElement(name = "Messages")
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class Messages {

        @XmlElement(name = "Message")
        private List<Message> messages = new ArrayList<Message>();

        public List<Message> getMessages() {
            return messages;
        }

    }
}