Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class Main {

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

        Root root = new Root();
        DatatypeFactory dtf = DatatypeFactory.newInstance();
        root.month = dtf.newXMLGregorianCalendar("--11");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class Root {

        @XmlElement(name = "Month")
        @XmlSchemaType(name = "gMonth")
        @XmlJavaTypeAdapter(GMonthAdapter.class)
        protected XMLGregorianCalendar month;

    }

    public static class GMonthAdapter extends XmlAdapter<String, XMLGregorianCalendar> {

        DatatypeFactory dtf;

        public GMonthAdapter() {
            try {
                dtf = DatatypeFactory.newInstance();
            } catch (DatatypeConfigurationException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public XMLGregorianCalendar unmarshal(String v) throws Exception {
            return dtf.newXMLGregorianCalendar(v);
        }

        @Override
        public String marshal(XMLGregorianCalendar v) throws Exception {
            String string = v.toXMLFormat();
            if (string.endsWith("--")) {
                return string.substring(0, 4);
            }
            return string;
        }

    }

}