Unmarshal XML to Arrays

I want an unmarhal XML file in an array of elements.

Example:

<root> <animal> <name>barack</name> </animal> <animal> <name>mitt</name> </animal> </root> 

I need an array of Animal elements.

When i try

 JAXBContext jaxb = JAXBContext.newInstance(Root.class); Unmarshaller jaxbUnmarshaller = jaxb.createUnmarshaller(); Root r = (Root)jaxbUnmarshaller.unmarshal(is); system.out.println(r.getAnimal.getName()); 

this screen is mitt , the last Animal.

I would like to do this:

 Animal[] a = .... // OR ArrayList<Animal> = ...; 

How can i do

+7
source share
1 answer

You can do the following:

Root

This example will work the same way if the field was changed to List<Animal> or ArrayList<Animal> .

 package forum13178824; import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Root { @XmlElement(name="animal") private Animal[] animals; } 

Animal

 package forum13178824; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class Animal { private String name; } 

Demo

 package forum13178824; import java.io.File; import javax.xml.bind.*; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Root.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File xml = new File("src/forum13178824/input.xml"); Root root = (Root) unmarshaller.unmarshal(xml); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(root, System.out); } } 

Input.xml / output

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <root> <animal> <name>barack</name> </animal> <animal> <name>mitt</name> </animal> </root> 

Additional Information

+9
source

All Articles