Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
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(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Root root = (Root) unmarshaller.unmarshal(new File("input.xml"));

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

    @XmlRootElement
    public static class Root {

        @XmlAttribute
        @XmlJavaTypeAdapter(BooleanAdapter.class)
        private Boolean a;

        public boolean isA() {
            return a;
        }

        public void setA(String s) {
            this.a = "yes".equals(s) || "on".equals(s) || "in".equals(s);
        }

    }

    public static class BooleanAdapter extends XmlAdapter<String, Boolean> {

        @Override
        public Boolean unmarshal(String s) throws Exception {
            return "yes".equals(s) || "on".equals(s) || "in".equals(s);
        }

        @Override
        public String marshal(Boolean b) throws Exception {
            if (b) {
                return "yes";
            }
            return "no";
        }

    }
}