I want to unmarshal a xml file containing a collection of data, like this
Jim
Tom<
JAXB:
unmarshaller.unmarshal(node, Person.class)
There are also advanced techniques with programmaticaly created mappings.
Look for a way to tell Castor that you'd like it to generate a java.util.List
of Person instances.
http://www.castor.org/how-to-map-a-list-at-root.html
You could use a StAX parser and do something like the following with any JAXB implementation (Metro, EclipseLink MOXy, Apache JaxMe, etc):
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.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
public class Demo {
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());
}
}
}
input.xml
<Persons>
<Person>Jim</Person>
<Person>Tom</Person>
</Persons>
System Output
Jim
Tom
Person
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
@XmlRootElement(name="Person")
public class Person {
private String name;
@XmlValue
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}