How to read same XML file more times using XMLStreamReader

1k views Asked by At

I read xml file in three phases and in each phase, I am interested in different elements, based on input parameters.

What is the best approach to read one xml file more times using XMLStreamReader?

xmlInputFactory = XMLInputFactory.newInstance();
    try {
        XMLStreamReader streamReader xmlInputFactory.createXMLStreamReader(inputStream);

 try {
        while (streamReader .hasNext()) {

where inputStream is FileInputStream instance

At the moment, I get either stream closed exception or streamReader.hasNext() is false when I start second phase reading.

2

There are 2 answers

0
ControlAltDel On

Load the file into memory and use a ByteArrayInputStream

File f = ...;
int len = (int)f.length(); // careful: If the life is over 4 gigs this won't work
byte myXML[] = new byte[];
FileInputStream fis = new FileInputStream(f);
int read = fis.read(f); // not guarenteed to read all bytes, but in my experience, this reads all bytes
if (read != len) throw RuntimeExcption("Didn't read everything");

// Now you can create as many XMLStreamReaders as you want like

    try {
        XMLStreamReader streamReader xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(buf));
0
Jordi Castilla On

Using XMLStreamReader you must iterate over the XML three times if the data you want to reach is not in a sequential order.

If you want to read only once, you can store data in global variables you can fill during the reading making three phases in one.

But if you need to finish first phase to start second, I would recommend you to use JaxB, it will convert your XML in a Java Object based in the XSD Schema making easier to manipulate the XML in a non-sequential way.