How to unmarshal xml without mapping the root xml element?

后端 未结 3 1338
一生所求
一生所求 2021-01-15 23:11

I want to unmarshal a xml file containing a collection of data, like this

 
      Jim
      Tom<         


        
3条回答
  •  情话喂你
    2021-01-15 23:56

    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 persons = new ArrayList();
            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

    
        Jim
        Tom  
    
    

    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;
        }
    
    }
    

提交回复
热议问题