How to unmarshal xml without mapping the root xml element?
I want to unmarsha开发者_如何学JAVAl a xml file containing a collection of data, like this
 <Persons>
      <Person>Jim</Person>
      <Person>Tom</Person>  
  </Persons>
We know this can be done with two classess: Persons, Person using Castor , JAXB, or other frameworks.
But how to do without writing a collection class Persons ?
JAXB:
- Iterate over subelements of the incoming XML (DOM, SAX, StAX - whatever API suits you best)
- 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;
    }
}
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论