function json2xml() {
    // console.clear();
    var obj = localStorage.getItem("json");

    console.log(obj);
    // console.log('***********************************************************');

    function createXMLDocument(namespace = null) {
        if (typeof document.implementation.createDocument === 'function') {
            return document.implementation.createDocument(namespace, '', null);
        } else if (typeof ActiveXObject !== 'undefined') {
            // For Internet Explorer
            var versions = ['MSXML2.DOMDocument.6.0', 'MSXML2.DOMDocument.3.0', 'Microsoft.XMLDOM'];
            for (var i = 0; i < versions.length; i++) {
                try {
                    var xmlDoc = new ActiveXObject(versions[i]);
                    return xmlDoc;
                } catch (e) {
                    console.log(e);
                }
            }
        }
        throw new Error('Your browser or environment does not support XML document creation.');
    }

    function createElementWithText(xmlDoc, parentElement, elementName, textContent, attributes = {}) {
        var element = xmlDoc.createElement(elementName);
        if (Object.keys(attributes).length != 0) {
            for (const key in attributes) {
                element.setAttribute(key, attributes[key])
            }

        }
        element.appendChild(xmlDoc.createTextNode(textContent));
        return parentElement.appendChild(element);

    }

    function createStandaloneXMLNode(tagName, attributes = {}, textContent = '') {
        // console.log(attributes);
        const xmlDoc = createXMLDocument();
        const element = xmlDoc.createElement(tagName);

        for (const attributeName in attributes) {
            element.setAttribute(attributeName, attributes[attributeName]);
        }

        if (textContent !== '') {
            const textNode = xmlDoc.createTextNode(textContent);
            element.appendChild(textNode);
        }

        return {
            'doc': xmlDoc,
            'element': element
        };
    }

    function getXMLNodesOfQuestionData(question) {

        var {
            doc,
            element
        } = createStandaloneXMLNode('Question', {
            // "xsi:type": (question['question_type'] == 'text' ? 'DescriptiveQuestion' : 'MultiChoiceQuestion'),
            'Id': (question['question_type'] == 'text' ? question['text_question_uuid'] : question['choice_question_uuid']),
            'Type': (question['question_type'] == 'text' ? 'Descriptive' : 'MCQ'),
            'No': (question['question_id']  ? question['question_id'] : question['questionChoiceId']),
            'DisplayMarks': (question['display_marks'] === true ? 'true' : 'false'),
            
        }, '');


        var questionTitle = createElementWithText(doc, element, 'Text', question['question']);
        if(question['is_math_enabled2'] === true){
            questionTitle.setAttribute('Type',(question['is_math_enabled2'] === true ? 'Math' : ''));
        }
        var questionDesc = createElementWithText(doc, element, 'Subtext', question['question_description']);
        if(question['is_math_enabled'] === true){
            questionDesc.setAttribute('Type',(question['is_math_enabled'] === true ? 'Math' : ''));
        }
        var marks = createElementWithText(doc, element, 'Marks', question['marks']);
        
        if (question['question_type'] == 'group') {
            // console.log(question);
            separateCorrectAnswerFromMcqAsJson(question)
            var hasMultipleAnswers = createElementWithText(doc, element, 'HasMultipleAnswers', (question['question_sub_type'] === true ? 'true' : 'false'), {});
            var choicesElement = createElementWithText(doc, element, 'Choices', '', {});
                        for (choice in question['answers']) {
                var choiceElement = createElementWithText(doc, choicesElement, 'Choice', '', {});
                                var id = createElementWithText(doc, choiceElement, 'Id', question['answers'][choice]['choice_uuid'], {});
                var no = createElementWithText(doc, choiceElement, 'No', question['answers'][choice]['no'], {});
                var text = createElementWithText(doc, choiceElement, 'Text', question['answers'][choice]['choice_name'], {});
                if(question['answers'][choice]['is_math_enabled'] === true){
                    text.setAttribute('Type',(question['answers'][choice]['is_math_enabled'] === true ? 'Math' : ''));
                }

                        }
            // choicesElement.appendChild();
        }

        return element;

    }

    function getXMLNodesOfGroupQuestionData(singleQuestion){
       
        console.log(singleQuestion);
        //create question group title related xml nodes
        var {
            doc,
            element
        } = createStandaloneXMLNode('Question', {
            // 'xsi:type': 'QuestionGroup',
            'Id': singleQuestion['group_uuid'],
            'Type': 'QuestionGroup',
            'No': (singleQuestion['question_id'] ? singleQuestion['question_id'] : '' ),
            'DisplayMarks':(singleQuestion['group_display_marks']  === true ? 'true' : 'false' ),
            ...(singleQuestion['group_attempt_any'] !== '' ? {'AttemptAny': singleQuestion['group_attempt_any']} : {})
        }, '');


    var groupQuestionTitle = createElementWithText(doc, element, 'Text', singleQuestion['group_title']);
    var groupQuestionDesc = createElementWithText(doc, element, 'Subtext', singleQuestion['group_description']);
    var groupQuestionMarks = createElementWithText(doc, element, 'Marks', singleQuestion['group_marks']);
    var groupQuestionItemsElement = createElementWithText(doc, element, 'Items', '');

    //gather questions data inside question group
    if (singleQuestion['questions'].length != 0) {
        var tempGroupQuestions = singleQuestion['questions'];
        // console.log(tempGroupQuestions);
        //looping each questions indise question group and attach it to group items node
        for (gquestion in tempGroupQuestions) {
            var singleGQuestion = tempGroupQuestions[gquestion];
            // console.log('singleGQuestion-'+gquestion);
            // console.log(singleGQuestion);
            // console.log('***********************************');
            if (singleGQuestion.hasOwnProperty('question_type')) // normal questions inside group questions
            {
                console.log('Single Question');
                var singleGQuestionElement = getXMLNodesOfQuestionData(singleGQuestion);
                //attach into group items node
                groupQuestionItemsElement.appendChild(singleGQuestionElement);
            }
            else
            {
                // console.log('Group Question');
                var multiGQuestionElement = getXMLNodesOfGroupQuestionData(singleGQuestion);
                groupQuestionItemsElement.appendChild(multiGQuestionElement);
            }
        }
    }

    return element;

    }

    //start of the busi logic
    questionPaper = JSON.parse(obj);
    // console.log(questionPaper);
    var ns1 = 'http://www.w3.org/2001/XMLSchema';
    var xmlDoc = createXMLDocument(namespace = ns1);
    var rootElement = xmlDoc.createElement('QuestionPaper');
    rootElement.setAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance');
	rootElement.setAttribute('xmlns:xsd','http://www.w3.org/2001/XMLSchema');
	rootElement.setAttribute('Id', questionPaper.question_Paper_uuid);
    rootElement.setAttribute('MaxMarks',questionPaper.max_marks);
	rootElement.setAttribute('CourseId',questionPaper.course_ID);
    rootElement.setAttribute('CourseCode',questionPaper.course_Code);
	rootElement.setAttribute('SubjectId',questionPaper.subject_ID);
    rootElement.setAttribute('SubjectCode',questionPaper.subject_Code);
	rootElement.setAttribute('PaperNo',questionPaper.paper_No);
    rootElement.setAttribute('SubjectName',questionPaper.subject_Name);
	rootElement.setAttribute('SubPaperPrefix',questionPaper.sub_Paper_Prefix);
    xmlDoc.appendChild(rootElement);

    
    createElementWithText(xmlDoc, rootElement, 'Title', questionPaper.question_paper_title);
    createElementWithText(xmlDoc, rootElement, 'Subtitle', questionPaper.question_paper_description);
    var rootItemsElement = createElementWithText(xmlDoc, rootElement, 'Items', '', );

    //iterate each sections
    for (section in questionPaper['sections']) {
        //create section related xml nodes
        var tempSection = questionPaper['sections'][section];
        var sectionNumber = parseInt(section);
        sectionNumber++
        // console.log(tempSection);

        var sectionElement = createElementWithText(xmlDoc, rootItemsElement, 'Question', '', {
            // 'xsi:type': 'QuestionPaperSection',
            'Id': tempSection['section_uuid'],
            'Type': 'Section',
            'No': sectionNumber,
            'DisplayMarks':(tempSection['section_display_marks']  === true ? 'true' : 'false'),
            ...(tempSection['section_attempt_any'] !== '' ? {'AttemptAny': tempSection['section_attempt_any']} : {}),
        });

        var sectionTitle = createElementWithText(xmlDoc, sectionElement, 'Text', tempSection['section_title']);
        var sectionDesc = createElementWithText(xmlDoc, sectionElement, 'Subtext', tempSection['section_description']);
        var sectionMarks = createElementWithText(xmlDoc, sectionElement, 'Marks', tempSection['section_marks']);
        // var sectionDisplayMark = createElementWithText(xmlDoc, sectionElement, 'DisplayMarks', (tempSection['section_display_marks']  === true ? 'true' : 'false'));
        // var sectionAttempAny = createElementWithText(xmlDoc, sectionElement, 'AttemptAny', tempSection['section_attempt_any']);
        var sectionItemElement = createElementWithText(xmlDoc, sectionElement, 'Items', '', );


        //gather questions data
        if (tempSection['questions'].length != 0) {
            for (question in tempSection['questions']) {
                var singleQuestion = tempSection['questions'][question];

                
                //for Separate Correct Answer From MCQ 
                if(singleQuestion.question_type == 'group'){
                    console.log(singleQuestion);
                    separateCorrectAnswerFromMcqAsJson(singleQuestion,12)
                }


                if (singleQuestion.hasOwnProperty('question_type')) // normal questions
                {

                    var singleQuestionElement = getXMLNodesOfQuestionData(singleQuestion);
                                        //attach each single question into section item node
                    sectionItemElement.appendChild(singleQuestionElement);
                } else // handle question group
                {

                    var groupQuestionElement =  getXMLNodesOfGroupQuestionData(singleQuestion);
                                        sectionItemElement.appendChild(groupQuestionElement);
                }

            }
        }

        rootItemsElement.appendChild(sectionElement);
    }
    rootElement.appendChild(rootItemsElement);

    // Serialize the XML to a string
    var xmlString = new XMLSerializer().serializeToString(xmlDoc);

    console.log(xmlString);
    localStorage.setItem("xml", xmlString);

}


const outputJson = { questions: [] };

function separateCorrectAnswerFromMcqAsJson(tempSection,check=0) {

    console.log(check);
    var answers= [];
const questionId = tempSection.choice_question_uuid;
var correct_answers = tempSection.correct_answer;
    correct_answers.forEach(function(answer){
       answers.push(answer[0])
    });
// Create an object for each question and push it to the output array
outputJson.questions.push({
    questionId,
    answers
});

// Convert the output object to JSON string
console.log(outputJson);

function removeDuplicateQuestionIds(inputJson) {
    const uniqueQuestionIds = {};
    const result = { questions: [] };
  
    for (const question of inputJson.questions) {
      const questionId = question.questionId;
  
      // Check if questionId is not already added
      if (!uniqueQuestionIds[questionId]) {
        uniqueQuestionIds[questionId] = true;
        result.questions.push(question);
      }
    }
  
    return result;
  }
  
  const uniqueOutputJson = removeDuplicateQuestionIds(outputJson);

const outputJsonString = JSON.stringify(uniqueOutputJson, null, 2);
localStorage.setItem("Correct_Answer_Json", outputJsonString);
// console.log('outputJsonString : ', outputJsonString);

}

