2

I am getting the below response from a webservice call

<response>
<status>sucecss</status>
<Message>xyz..........</Message>
</response>

I have trying to prase this response from DOM.

Dom.XMLNode response = doc.getRootElement();
oResponse.Status = response.getChildElement('status', null).getText();
oResponse.Message = response.getChildElement('Message', null).getText();

but it throws an error because sometime Message does not come .

I have tried with XMLStreamreader. but again it's going to infinite loop.. and throwing null value

Xmlstreamreader reader = new Xmlstreamreader(Requestequest);
while(reader.hasNext()) {
        if (reader.getEventType() == XmlTag.START_ELEMENT) {
            if ('Status' == reader.getLocalName()) {
                  if (reader.getEventType() == XmlTag.END_ELEMENT) {
                        break;
                    } else if (reader.getEventType() == XmlTag.CHARACTERS) {
                        reponse.status = reader.getText();
                    }

                }  
            if ('Message' == reader.getLocalName()) {
                 if (reader.getEventType() == XmlTag.END_ELEMENT) {
                        break;
                    } else if (reader.getEventType() == XmlTag.CHARACTERS) {
                        reponse.message = reader.getText();
                    }   
             }
        reader.next();
    } 
    system.debug('********************' + oresponse);
    return oresponse;
}

1 Answer 1

2

Unless the XML is very large, reading the XML into a DOM is the way to go.

If an element is missing you need to first check for that before trying to get the text of the element. So change:

oResponse.Message = response.getChildElement('Message', null).getText();

to:

Dom.XmlNode message = response.getChildElement('Message', null);
oResponse.Message = message != null ? message.getText() : null;

And make similar changes for any other optional elements.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .