Java XmlStreamReader-class And Method Code Example


Here is an example of how to use the XmlStreamReader class from the Apache Commons IO library to read an XML file and print its elements in Java:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.commons.io.input.XmlStreamReader;

public class XmlStreamReaderExample {
    public static void main(String[] args) throws IOException, XMLStreamException {
        FileInputStream inputStream = new FileInputStream(new File("path/to/file.xml"));
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = new XmlStreamReader(inputStream, factory);

        while (reader.hasNext()) {
            int event = reader.next();
            if (event == XMLStreamReader.START_ELEMENT) {
                System.out.println("Start Element: " + reader.getLocalName());
            } else if (event == XMLStreamReader.END_ELEMENT) {
                System.out.println("End Element: " + reader.getLocalName());
            }
        }

        inputStream.close();
    }
}

In this example, an input stream is created to read the XML file located at "path/to/file.xml" and it is wrapped with a XmlStreamReader. Then, it uses a while loop to iterate over the elements of the XML file and the event type is checked to determine if it is a start element or an end element. If it is a start element, the local name of the element is printed, and if it is an end element, the local name of the element is printed.

It is important to note that the XmlStreamReader class is a wrapper for the javax.xml.stream.XMLStreamReader class, and it provides a convenient way to create an XMLStreamReader instance with a default XMLInputFactory and encoding.

Finally, the input stream is closed after reading the file.