Search code examples
javaxmlstax

StAX get current event after calling getElementText()


Per stax specification, the getElementText() returns the text data and places the current event as the END_ELEMENT.

How do I get access to this END_ELEMENT, as the XMLEventReader does not have any method to access the current event? peek() and next() methods provide next event in the XML.


Solution

  • Your Better off interpreting the events

                while (eventReader.hasNext()) {
                XMLEvent event = eventReader.nextEvent();
    
                if (event.isStartElement()) {
                    StartElement startElement = event.asStartElement();
    
                    // check the element
                    if (startElement.getName().getLocalPart() == ("MyTag")) {
    
                        // We read the attributes from this tag
    
                        @SuppressWarnings("unchecked")
                        Iterator<Attribute> attributes = (Iterator<Attribute>) startElement
                                .getAttributes();
                        while (attributes.hasNext()) {
                            Attribute attribute = attributes.next();
                            if (attribute.getName().toString().equals("myattribute")) {
                                System.out.println("Attribute Value: " + attribute.getValue());
                            }
                        }
                    }
    
                    if (event.isEndElement()) {
                    EndElement endElement = event.asEndElement();
                        if (endElement.getName().getLocalPart() == ("MyTag")) { 
                        // do Something 
                        }
                    }
                } // end while