[SalesForce] XMLStreamWriter: Cannot User getText on START_ELEMENT

I have a requirement to get the text of the Start Element of XML. I'm using the XMLStreamWriter class. If My XML is as follows

 <errorReturned errorCode="100">This is a test</errorReturned>

And APEX is

        if(reader.getEventType() == XmlTag.START_ELEMENT && reader.getLocalName() == 'errorReturned'){

                String errorCode = reader.getAttributeValue(null, 'errorCode');
                System.debug('errorCodeFound=' + errorCode);                      
                String errorText = reader.                  
                System.debug('errorTextFound=' + errorText);
            }  

I can get the errorCode ok "100" but I get an error as follows if I try to use getText to get the actual error details

|System.XmlException: Illegal State: Current state START_ELEMENT is not among the statesCHARACTERS, COMMENT, CDATA, SPACE, ENTITY_REFERENCE, DTD valid for getText()

Any ideas on how I can get around this or access the text details would be appreciated.

Thanks in advance.

Best Answer

You can only use getText() when you are in a valid state; therefore, you must first call next() to advance to the next event, then check and make sure that you are in a valid state (e.g. XmlTag.CHARACTERS) before attempting to use getText().

if(reader.getEventType() == XmlTag.START_ELEMENT && reader.getLocalName() == 'errorReturned'){

                String errorCode = reader.getAttributeValue(null, 'errorCode');
                System.debug('errorCodeFound=' + errorCode);
                // Advance to next CHARACTERS event
                while(reader.hasNext() && reader.next() != XmlTag.CHARACTERS);
                // If we haven't reached end of stream, and we have a character event...
                if(reader.getEvent() == XmlTag.CHARACTERS) {
                    String errorText = reader.getText();
                    System.debug('errorTextFound=' + errorText);
                }
            }  
Related Topic