External app will send XML in their request to salesforce webservice class and webservice class will have to insert a object record.I have written a webservice and it is able to get the xml in string variable.and I am executing this class by passing sample xml in workbench.

This is the sample XML

<?xml version="1.0" encoding="UTF-8"?>

Wbeservice class


global class createExamHistory{

    global static void createExamHistory() {

        RestRequest req = RestContext.request;
        System.debug('req is---------------------- ' +req);
        RestResponse resp = RestContext.response;
        String xmloutput  = EncodingUtil.base64Decode(EncodingUtil.base64Encode(req.requestbody)).toString();
       XmlStreamReader reader = new XmlStreamReader(xmloutput);
       String examId= readResponse(reader);


     public static String readResponse(XmlStreamReader reader) {

        Exam_History__c examHistory;
        List<Exam_History__c> examHistoryList = new list<Exam_History__c>();
        String historyId;

        while (reader.hasNext()) { 
            if (reader.getEventType() == XmlTag.START_ELEMENT) {

              if ('exam-history' == reader.getLocalName()) {
                   examHistory = new Exam_History__c ();
              }else if ('due_date' == reader.getLocalName()) {
                   examHistory.Due_Date__c= Date.valueOf(getValueFromTag(reader));
              }else if (reader.getEventType() == XmlTag.END_ELEMENT) {
            // Is the next element an end tag?
            if ('exam-history' == reader.getLocalName()) {
                insert examHistory;
                historyId = [select id from Exam_History__c where id=:examHistory.id].id;
   return historyId;
   // insert examHistoryList;

  public static string getValueFromTag(XMLStreamReader reader) {
    String DataValue;

    while (reader.hasNext()) {
        if (reader.getEventType() == XmlTag.END_ELEMENT) {
        } else if (reader.getEventType() == XmlTag.CHARACTERS) {
            DataValue = reader.getText();

    return DataValue;


After executing with workbench,getting apex error: System.LimitException: Apex CPU time limit exceeded Error is at while (reader.hasNext()).


You have an infinite loop.


Is always true because you never actually increment it or move to the next element in the reader. The only time you move to the next element is when you are on the <due_date> element, which is never the first element.

Add the following to the end of your loop to ensure you always move to the next element:

  1. Class documentation
  2. Class Examples

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.