I need to build a HTML form from an XML string using Javascript/jQuery.
I came through the below answer
The answer talks about this - XML to Form generator
That's exactly what i want, but i could not find the javascript code in the provided link. I have tried parsing the XML string and iterating through nodes to build the Form, but there are lots of bugs in my code and i am short of time. Below is the code i tried:
function xmlToForm(text) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text,"text/xml");
var htmlForm = '<form action="">';
var rootNode = xmlDoc.childNodes[0];
htmlForm += nodeToHtmlForm(rootNode);
htmlForm += '</form>';
function nodeToHtmlForm (node) {
var form = '';
if(node.childNodes.length > 0) {
node.childNodes.forEach(function(childNode) {
if(childNode.childNodes.length > 0) {
if(childNode.firstChild.nodeValue) {
form += '<div class="form-group">'
form += '<label><h4>'+ childNode.nodeName +'</h4>'+ '</label>';
form += '<input class="" id="id" value=' + childNode.firstChild.nodeValue + '>';
form += '</div>'
} else {
}
form += '<br><h4>'+ childNode.nodeName +'</h4><br>'
childNode.childNodes.forEach(function(grandChildNode) {
console.log(grandChildNode);
form += nodeToHtmlForm(grandChildNode)
});
}
else {
form += '<div class="form-group">'
form += '<label>'+node.nodeName+'</label>';
form += '<input class="" id="id" value='+node.firstChild.nodeValue+'>';
form += '</div>'
}
});
} else {
if(node.firstChild) {
form += '<div class="form-group">'
form += '<label>'+node.nodeName+'</label>';
form += '<input class="" id="id" value='+node.firstChild.nodeValue+'>';
form += '</div>'
} else {
form += '<br><h4>'+ node.nodeName +'</h4><br>';
}
}
return form;
}
return htmlForm;
//document.getElementById("htmlForm").innerHTML = htmlForm;
}
Someone please help me build the HTML form from XML.