Example usage for javax.xml.bind Unmarshaller unmarshal

List of usage examples for javax.xml.bind Unmarshaller unmarshal

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller unmarshal.

Prototype

public Object unmarshal(javax.xml.stream.XMLEventReader reader) throws JAXBException;

Source Link

Document

Unmarshal XML data from the specified pull parser and return the resulting content tree.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Root.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xml = new File("input.xml");
    Root root = (Root) unmarshaller.unmarshal(xml);

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

From source file:Main.java

public static void main(String args[]) throws Exception {
    Order o = new Order();
    o.setCustId(123);/*  w  w  w  .j  a v  a 2 s  .  c o m*/
    o.setDescription("New order");
    o.setOrderDate(new Date());

    List<Item> items = new ArrayList<Item>();

    Item i = new Item();
    i.setName("PC");
    i.setQty(10);
    items.add(i);

    i = new Item();
    i.setName("Box");
    i.setQty(4);

    items.add(i);

    o.setItems(items);
    // Write it
    JAXBContext ctx = JAXBContext.newInstance(Order.class);

    Marshaller m = ctx.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter sw = new StringWriter();
    m.marshal(o, sw);
    sw.close();
    System.out.println(sw.toString());

    // Read it back
    JAXBContext readCtx = JAXBContext.newInstance(Order.class);
    Unmarshaller um = readCtx.createUnmarshaller();

    Order newOrder = (Order) um.unmarshal(new StringReader(sw.toString()));
    System.out.println(newOrder);
}

From source file:Main.java

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

    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(new File("input.xml")));

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    unmarshaller.setListener(new LocationListener(xsr));
    Customer customer = (Customer) unmarshaller.unmarshal(xsr);
}

From source file:Main.java

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);/*  www .ja  v  a  2  s. co m*/
        xsr.nextTag();
    }

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

From source file:Main.java

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

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    StringReader xml = new StringReader(
            "<person><id>123</id><first-name>Tom</first-name><last-name>Smith</last-name></person>");
    Person person = (Person) unmarshaller.unmarshal(xml);

    System.out.println(person.id);
    System.out.println(person.firstName);
    System.out.println(person.lastName);
}

From source file:org.jasig.portlet.maps.tools.MapDataTransformer.java

/**
 * @param args//from   w  w  w . j  a  v  a2  s .c  o m
 */
public static void main(String[] args) {

    // translate the KML file to the map portlet's native data format
    File kml = new File("map-data.xml");
    File xslt = new File("google-earth.xsl");

    try {
        TransformerFactory transFact = javax.xml.transform.TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer(new StreamSource(xslt));
        trans.transform(new StreamSource(kml), new StreamResult(System.out));
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    // deserialize the map data from XML
    MapData data = null;
    try {
        JAXBContext jc = JAXBContext.newInstance(MapData.class);
        Unmarshaller u = jc.createUnmarshaller();
        data = (MapData) u.unmarshal(new FileInputStream(new File("map-data-transformed.xml")));
    } catch (JAXBException e1) {
        e1.printStackTrace();
        return;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    }

    // ensure each location has a unique, non-null abbreviation
    setAbbreviations(data);

    // update each location with an address
    //        setAddresses(data);

    // sort locations by name
    Collections.sort(data.getLocations(), new ByNameLocationComparator());

    // serialize new map data out to a file into JSON format
    try {
        mapper.defaultPrettyPrintingWriter().writeValue(new File("map.json"), data);
    } catch (JsonGenerationException e) {
        System.out.println("Error generating JSON data for map");
        e.printStackTrace();
    } catch (JsonMappingException e) {
        System.out.println("Error generating JSON data for map");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Error writing JSON data to map file");
        e.printStackTrace();
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Element> elementList = new ArrayList<Element>();
    List<Item> itemList = new ArrayList<Item>();
    Element element1 = new Element();
    Element element2 = new Element();
    Item item1 = new Item();
    Item item2 = new Item();
    Elements elements = new Elements();

    item1.setId(1);/*from   w  ww  . j  a v a 2 s. c  o  m*/
    item1.setName("Test1");
    item2.setId(2);
    item2.setName("Test2");
    itemList.add(item1);
    itemList.add(item2);

    element1.setProperty1("prop1");
    element1.setProperty2("prop2");
    element1.setType(2);
    element1.setItems(itemList);

    element2.setProperty1("prop11");
    element2.setProperty2("prop22");
    element2.setType(22);
    element2.setItems(itemList);

    elementList.add(element1);
    elementList.add(element2);

    elements.setElements(elementList);

    System.out.println("------- Object to XML -----------\n");
    JAXBContext jaxbContext = JAXBContext.newInstance(Elements.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    // output pretty printed
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(elements, System.out);

    System.out.println("\n------- XML to Object -----------\n");

    String xml = "<elements><element><items><item><id>1</id><name>Test1</name></item><item><id>2</id><name>Test2</name></item></items><property1>prop1</property1><property2>prop2</property2><type>2</type></element><element><items><item><id>1</id><name>Test1</name></item><item><id>2</id><name>Test2</name></item></items><property1>prop11</property1><property2>prop22</property2><type>22</type></element></elements>";
    StringReader reader = new StringReader(xml);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Elements elementsOut = (Elements) jaxbUnmarshaller.unmarshal(reader);
    System.out.println(elementsOut);

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Root.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    // Unmarshal #1 = Default Unmarshal
    System.out.println("Unmarshal #1");
    Root root = (Root) unmarshaller.unmarshal(new StringReader(XML));
    marshaller.marshal(root, System.out);

    // Unmarshal #2 - Override Default ValidationEventHandler
    System.out.println("Unmarshal #2");
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override//w w  w. j a  v a  2s.  c o m
        public boolean handleEvent(ValidationEvent event) {
            System.out.println(event.getMessage());
            return false;
        }
    });
    unmarshaller.unmarshal(new StringReader(XML));
}

From source file:webservices.simple_jaxb.UnmarshalRead.java

public static void main(String[] args) {
    try {//from  w w  w  . ja v a2s. c  o  m
        // create a JAXBContext capable of handling classes generated into
        // the primer.po package
        JAXBContext jc = JAXBContext.newInstance("primer.po");

        // create an Unmarshaller
        Unmarshaller u = jc.createUnmarshaller();

        // unmarshal a po instance document into a tree of Java content
        // objects composed of classes from the primer.po package.
        JAXBElement<?> poElement = (JAXBElement<?>) u.unmarshal(new File("po.xml"));
        PurchaseOrderType po = (PurchaseOrderType) poElement.getValue();

        // examine some of the content in the PurchaseOrder
        System.out.println("Ship the following items to: ");

        // display the shipping address
        USAddress address = po.getShipTo();
        displayAddress(address);

        // display the items
        Items items = po.getItems();
        displayItems(items);

    } catch (JAXBException je) {
        je.printStackTrace();
    }
}

From source file:eu.impact_project.iif.tw.cli.ToolWrapper.java

/**
 * Main method of the command line application
 *
 * @param args/*from   w ww. j  ava 2s . com*/
 *        Arguments of the command line application
 * @throws GeneratorException
 *         Exception if project generation fails
 */
public static void main(String[] args) throws GeneratorException {

    CommandLineParser cmdParser = new PosixParser();
    try {
        // Parse the command line arguments
        CommandLine cmd = cmdParser.parse(OPTIONS, args);
        // If no args or help selected
        if ((args.length == 0) || (cmd.hasOption(HELP_OPT))) {
            // OK help needed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(Constants.PROJECT_NAME, OPTIONS, true);

            if (args.length == 0)
                logger.info("Reading default configuration files from working " + "directory ...");
            else
                System.exit(0);
        }

        String toolspecPath = cmd.getOptionValue(TOOLSPEC_OPT, Constants.DEFAULT_TOOLSPEC);
        File toolspecFile = new File(toolspecPath);
        String propertiesPath = cmd.getOptionValue(PROPERTIES_OPT, Constants.DEFAULT_PROJECT_PROPERTIES);
        File propertiesFile = new File(propertiesPath);
        ioc.setXmlConf(toolspecFile);
        ioc.setProjConf(propertiesFile);

    } catch (ParseException excep) {
        // Problem parsing the command line args, just print the message and help
        logger.error("Problem parsing command line arguments.", excep);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Constants.PROJECT_NAME, OPTIONS, true);
        System.exit(1);
    }

    if (!ioc.hasConfig()) {
        throw new GeneratorException("No configuration available.");
    }
    JAXBContext context;
    try {
        context = JAXBContext.newInstance("eu.impact_project.iif.tw.toolspec");
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Toolspec toolspec = (Toolspec) unmarshaller.unmarshal(new File(ioc.getXmlConf()));
        // general tool specification properties
        logger.info("Toolspec model: " + toolspec.getModel());
        logger.info("Tool id: " + toolspec.getId());
        logger.info("Tool name: " + toolspec.getName());
        logger.info("Tool version: " + toolspec.getVersion());

        // List of services for the tool
        List<Service> services = toolspec.getServices().getService();
        // For each service a different maven project will be generated
        for (Service service : services) {
            createService(service, toolspec.getVersion());
        }
    } catch (IOException ex) {
        logger.error("An IOException occurred", ex);
    } catch (JAXBException ex) {
        logger.error("JAXBException", ex);
        throw new GeneratorException("Unable to create XML binding for toolspec");
    }
}