Ken Chan
Ken Chan

Reputation: 90427

Use JAXB to parse a XML file as a stream

I have a XML file which contains a lot of employees record (say up to 1M) as follows:

<employee>
 <name>peter</name>
 <mobile>435432</mobile>
<employee>
<employee>
 <name>Mary</name>
 <mobile>324213</mobile>
<employee>
<employee>
 <name>May</name>
 <mobile>54342423</mobile>
<employee>

I map an employee record using JAXB to the following Java object:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "employee")
public class Employee {
    @XmlElement(name = "name")
    private String name;

    @XmlElement(name = "mobile")
    private String mobile;
}

The content of the XML cannot be changed and given this XML , how can I use JAXB to unmarshal each employee XML record to Employee object such that I can process it one by one?

Upvotes: 2

Views: 974

Answers (1)

bdoughan
bdoughan

Reputation: 148977

You can parse the XML with a StAX XMLStreamReader then navigate to the first emoloyee element and unmarshal the XMLStreamReader at that state, then position it at the next emoloyee element and repeat.

UPDATE

My XML does not have a root element

You should be able to leverage a SequenceInputStream for your use case. You will create in on 3 instances of InputStream:

  1. One representing a start element you make up
  2. The second representing the content shown in your question
  3. The last representing the close element to the element you opened in the first InputStream.

Then pass the instance of SequenceInputStream to the XMLStreamReader I mentioned in my original answer and you should be good.

Upvotes: 2

Related Questions