I am trying to write an XML document from an HTML form using JavaScript with the following function:
JavaScript function:
JavaScript
x
17
17
1
function formToXml(form){
2
var xmldata=['<?xml version="1.0" encoding="UTF-8"?>'];
3
const elNames = ["author", "title"];
4
xmldata.push("<book>");
5
var inputs=form.elements;
6
for(var i=0;i<inputs.length;i++){
7
var el=document.createElement(elNames[i]);
8
if (inputs[i].name){
9
el.set("name",inputs[i].name);
10
el.setAttribute("value",inputs[i].value);
11
xmldata.push(el.outerHTML);
12
}
13
}
14
xmldata.push("</book>");
15
return xmldata.join("n");
16
}
17
The file that is generated has the following format:
JavaScript
1
6
1
<?xml version="1.0" encoding="UTF-8"?>
2
<book>
3
<author value="Something" name="author"/>
4
<title value="Something" name="title"/>
5
</book>
6
I am trying to modify the method in order for the nodes to have the following format:
JavaScript
1
3
1
<author>Something</author>
2
<title>Something</title>
3
I know that setAttribute() doesn’t work because it makes an attribute in the node. I can’t find a function that sets the value like the example above.
Any suggestions?
Advertisement
Answer
You can use the innerHTML
attribute on the element to set the value.
JavaScript
1
16
16
1
function formToXml(form) {
2
var xmldata = ['<?xml version="1.0" encoding="UTF-8"?>'];
3
const elNames = ["author", "title"];
4
xmldata.push("<book>");
5
var inputs = form.elements;
6
for (var i = 0; i < inputs.length; i++) {
7
var el = document.createElement(elNames[i]);
8
if (inputs[i].name) {
9
el.innerHTML = inputs[i].value; // Set the innerHTML of the element
10
xmldata.push(el.outerHTML);
11
}
12
}
13
xmldata.push("</book>");
14
return xmldata.join("n");
15
}
16
Example output:
JavaScript
1
6
1
<?xml version="1.0" encoding="UTF-8"?>
2
<book>
3
<author>Robert Louis Stevenson</author>
4
<title>Treasure Island</title>
5
</book>
6