Reputation: 53
Here is a smiple html form,I want to get the data from it and convert into xml or get the data in xml format?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="" method="post">
<p>
<label for="firstname">First Name:</label>
<input type="text" name="firstname" id="firstname">
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastname">
<button id="submitButton">submit</button>
</body>
</form>
</html>
Upvotes: 4
Views: 13466
Reputation: 4410
If you want a pure javascript solution for downloading any content you can use the following function:
function downloadData(contentType,data,filename){
var link=document.createElement("A");
link.setAttribute("href",encodeURI("data:"+contentType+","+data));
link.setAttribute("style","display:none");
link.setAttribute("download",filename);
document.body.appendChild(link); //needed for firefox
link.click();
setTimeout(function(){
document.body.removeChild(link); //only to remove the temporal link
},1000);
}
Where contentType
For creating XML data from a form you can use :
function fromToXml(form){
var xmldata=['<?xml version="1.0"?>'];
xmldata.push("<form>");
var inputs=form.elements;
for(var i=0;i<inputs.length;i++){
var el=document.createElement("ELEMENT");
if (inputs[i].name){
el.setAttribute("name",inputs[i].name);
el.setAttribute("value",inputs[i].value);
xmldata.push(el.outerHTML);
}
}
xmldata.push("</form>");
return xmldata.join("\n");
}
And then, try to modify the format as you expected.
See an example in https://jsfiddle.net/jmusfs9v/3/
If you are intenerested in generating a well-formed XML output from javascript you can follow the article: http://archive.oreilly.com/pub/h/2127
Upvotes: 1
Reputation: 1230
Try this code -
function getXml(){
var elements = document.forms.myForm.elements;
var xmlTemplate = '<?xml version="1.0"?> <formData>';
for(var i =0; i< elements.length; i++){
var element = elements[i];
if(element.tagName=="INPUT"){
xmlTemplate = xmlTemplate + '<'+element.name+'>' + element.value+'</'+element.name+'>';
}
}
xmlTemplate = xmlTemplate +'</formData>';
return xmlTemplate;
}
getXml();
Upvotes: 0