XMLStreamReader: hasNext() : XMLStreamReader « javax.xml.stream « Java by API






XMLStreamReader: hasNext()

  

import java.io.File;
import java.io.FileInputStream;

import javax.xml.stream.EventFilter;
import javax.xml.stream.StreamFilter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;

public class Main {
  public static void main(String[] args) throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileInputStream(new File("test.xml")));
    System.out.println(countEvents(reader));

    reader = inputFactory.createXMLStreamReader(new FileInputStream(new File("test.xml")));

    StreamFilter filter = new ElementOnlyFilter();
    reader = inputFactory.createFilteredReader(reader, filter);

    System.out.println(countEvents(reader));
  }
  private static int countEvents(XMLStreamReader reader) throws XMLStreamException {
    int counter = 1;
    while (reader.hasNext()) {
      reader.next();
      counter++;
    }
    return counter;
  }
}

class ElementOnlyFilter implements EventFilter, StreamFilter {
  public boolean accept(XMLEvent event) {
    return accept(event.getEventType());
  }

  public boolean accept(XMLStreamReader reader) {
    return accept(reader.getEventType());
  }

  private boolean accept(int eventType) {
    return eventType == XMLStreamConstants.START_ELEMENT
        || eventType == XMLStreamConstants.END_ELEMENT;
  }
}

   
    
  








Related examples in the same category

1.XMLStreamReader.getLocalName()
2.XMLStreamReader: getElementText()
3.XMLStreamReader: getEventType()
4.XMLStreamReader: getLocation()
5.XMLStreamReader: getName()
6.XMLStreamReader: getText()
7.XMLStreamReader: next()
8.XMLStreamReader: nextTag()
9.XMLStreamReader: require(int type, String namespaceURI, String localName)