This tutorial extends JAXB Tutorial for XML processing in Java step by step – unmarshall & marshall
When to use JAXB with StAX?
When you want to process large XML files, reading the whole file into memory can cause “OutOfMemoryError” as discussed in Java String & Array limitations and OutOfMemoryError post.
This approach is also good to process the middle of an XML document.
How to read the “book” author & title one by one?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0" encoding="utf-8"?> <books> <header> <name>Programming Books</name> </header> <book> <author>John Darcy</author> <title>Learning Java</title> </book> <book> <author>Peter Smith</author> <title>Learning Scala</title> </book> <footer> <records>2</records> </footer> </books> |
JAXB and StAX in action
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
package com.mytutorial; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; public class App { public static void main(String[] args) throws JAXBException, IOException, XMLStreamException, URISyntaxException { // Java 1.6 onwards JAXBContext jaxbContext = JAXBContext.newInstance(Books.class); // unmarshall: String "source" to Java object Unmarshaller um = jaxbContext.createUnmarshaller(); XMLInputFactory xmlFactory = XMLInputFactory.newInstance(); XMLStreamReader reader = xmlFactory.createXMLStreamReader(new FileReader(getFile())); // interested in "book" elements only. Skip up to first "book" while (reader.hasNext() && (!reader.isStartElement() || !reader.getLocalName().equals("book"))) { reader.next(); } // read a book at a time while (reader.getEventType() == XMLStreamConstants.START_ELEMENT) { JAXBElement<Book> boolElement = um.unmarshal(reader, Book.class); Book book = boolElement.getValue(); if (book.getAuthor() != null) { //skip footer tag System.out.println(book.getAuthor() + " wrote " + book.getTitle()); } if (reader.getEventType() == XMLStreamConstants.CHARACTERS) { reader.next(); } } reader.close(); } /** * * @return * @throws IOException * @throws URISyntaxException */ private static final File getFile() throws IOException, URISyntaxException { Path path = Paths.get(ClassLoader.getSystemResource("xml/books.xml").toURI()); return path.toFile(); } } |
Output:
1 2 3 4 |
John Darcy wrote Learning Java Peter Smith wrote Learning Scala |
(Visited 48 times, 2 visits today)