How to unmarshal xml without mapping the root xml element?

后端 未结 3 1332
一生所求
一生所求 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:40

    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.

    0 讨论(0)
  • 2021-01-15 23:42

    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

    0 讨论(0)
  • 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<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;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题