简体   繁体   中英

How to read same XML file more times using XMLStreamReader

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.

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));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM