Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {

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

        StringReader xml = new StringReader("<Address><Name>Test</Name></Address>");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Address address = (Address) unmarshaller.unmarshal(xml);

        System.out.println(address.getPostalAddress().getState());

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

    @XmlRootElement(name = "Address")
    public static class Address {

        private String name;
        private PostalAddress postalAddress;

        @XmlElement(name = "Name")
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @XmlElement(name = "PostalAddress")
        public PostalAddress getPostalAddress() {
            if (null == postalAddress) {
                postalAddress = new PostalAddress();
            }
            return postalAddress;
        }

        public void setPostalAddress(PostalAddress postalAddress) {
            this.postalAddress = postalAddress;
        }

    }

    public static class PostalAddress {

        private String state;

        @XmlElement(name = "State")
        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }
    }
}