Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

public class Main {

    public static void main(String[] args) throws Exception {
        XMLInputFactory xif = XMLInputFactory.newFactory();

        FileInputStream xml = new FileInputStream("input.xml");
        XMLStreamReader xsr = xif.createXMLStreamReader(xml);
        xsr.nextTag(); // Advance to "Persons" tag
        xsr.nextTag(); // Advance to "Person" tag

        JAXBContext jc = JAXBContext.newInstance(Person.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        List<Person> persons = new ArrayList<Person>();
        while (xsr.hasNext() && xsr.isStartElement()) {
            Person person = (Person) unmarshaller.unmarshal(xsr);
            persons.add(person);
            xsr.nextTag();
        }

        for (Person person : persons) {
            System.out.println(person.getName());
        }
    }

    @XmlRootElement(name = "Person")
    public static class Person {
        private String name;

        @XmlValue
        public String getName() {
            return name;
        }

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