Unmarshal XML into arrays
18,616
You could do the following:
Root
This example would work the same 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>
For More Information
- http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html
- http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
Author by
Olivier J.
Updated on July 19, 2022Comments
-
Olivier J. almost 2 years
I want to unmarhal XML file into array of elements.
Example :
<root> <animal> <name>barack</name> </animal> <animal> <name>mitt</name> </animal> </root>
I would like 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 display
mitt
, the last Animal.I would like to do this :
Animal[] a = .... // OR ArrayList<Animal> = ...;
How can I do please ?
-
Olivier J. over 11 yearsThank you ! Nice example and very nice blog ;)
-
Jaanus about 11 yearsI had to annotate
Root
also with@XmlAccessorType(XmlAccessType.FIELD)
-
pmartin8 over 8 yearsI don't think you can use @XmlAccessorType(XmlAccessType.FIELD) along with @XmlElement(name="animal"). Your mapping the same element twice...
-
bdoughan over 8 years@pmartin8 - You can't use
@XmlAccessorType(XmlAccessType.FIELD)
and then put@XmlElement
on an accessor method (get/set), but as long as you put it on a field (instance variable) you are fine.