You can do the following:
- Parse the XML with a StAX
XMLStreamReader
.
- Advance the
XMLStreamReader
to the element you wish to unmarshal.
- Use one of the unmarshal methods that take an
XMLStreamReader
.
Example
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;
public class UnmarshalDemo {
public static void main(String[] args) throws Exception {
// Parse the XML with a StAX XMLStreamReader
XMLInputFactory xif = XMLInputFactory.newFactory();
StreamSource xml = new StreamSource("input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
// Advance the XMLStreamReader to the element you wish to unmarshal
xsr.nextTag();
while(!xsr.getLocalName().equals("device")) {
xsr.nextTag();
}
// Use one of the unmarshal methods that take an XMLStreamReader
JAXBContext jc = JAXBContext.newInstance(Device.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Device device = (Device) unmarshaller.unmarshal(xsr);
xsr.close();
}
}
For More Information