Search code examples
javaxmlstax

StAX find Corresponding End Tag?


Is it possible / is there an easy way to find an end tag (END_ELEMENT) corresponding to a START_ELEMENT as in the following?

while(reader.hasNext()){
        XMLEvent event = reader.nextEvent();

        if(event.getEventType() == XMLEvent.START_ELEMENT){
            StartElement startElement = event.asStartElement();
            System.out.println(startElement.getName().getLocalPart());
        }
    }

Solution

  • If you by the mean the easy way to have a call to return the end element the answer is no. SAX parsers are event based parsers, so it read your XML file and create events. It is up to you to handle these events and build your memory structure as these events come.

    Maybe you should use a DOM parser which builds up the XML structure in the memory and you can navigate in it. Or use some xml bindig (e.g JAXB) which translate an XML to java objects and vica-versa.