Create XML StAX reader from file - Java XML

Java examples for XML:StAX

Description

Create XML StAX reader from file

Demo Code


//package com.java2s;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import java.io.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        String filename = "java2s.com";
        System.out.println(createXmlReaderFromFile(filename));
    }//from ww w .  j  ava 2  s.  c  o m

    /**
     * Create XML reader from file
     *
     * @param filename
     * @return
     * @throws IOException
     * @throws XMLStreamException
     */
    static XMLEventReader createXmlReaderFromFile(String filename)
            throws IOException, XMLStreamException {
        String data = getXmlDataFromFile(filename);
        return createXmlReader(data);
    }

    private static String getXmlDataFromFile(String filename)
            throws IOException {
        try (BufferedReader bufferedReader = new BufferedReader(
                new FileReader(new File(filename)))) {
            String line;
            StringBuilder xmlData = new StringBuilder();

            while ((line = bufferedReader.readLine()) != null) {
                xmlData.append(line);
            }

            return xmlData.toString();
        }
    }

    /**
     * Create XML reader from data string
     *
     * @param xmlData
     * @return
     * @throws XMLStreamException
     */
    static XMLEventReader createXmlReader(String xmlData)
            throws XMLStreamException {
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        return inputFactory.createXMLEventReader(new StringReader(xmlData));
    }
}

Related Tutorials