2

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.

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.