I am looking to create an XML schema from an array in the object. The length of the array varies and based on that I would like to create a logic that generates the response. Below is the format and example.
Object - Exact
"Data": [{
"JK": true,
"Number": "02154029",
"Name": "Allen",
"Type": "Delta",
"Code": "ASM",
"Amount": 10
},
{
"JK": true,
"Number": "92154429",
"Name": "Peter",
"Type": "Delta",
"Code": "FLSM",
"Amount": 50
},
.
.
.
.
"n items"
]
Above is the object that varies its length, using the above object I would like to create the below XML schema.
XML - Expected
<request ...........>
<delta.....>
<lineItem id = 1....>
</lineItem>
<lineItem id = 2....>
</lineItem>
.
.
.
<lineItem id = n....>(based on length of above array)
</lineItem>
<params amount = "10" code = "ASM" batch = "1">
<params amount = "50" code = "FLSM" batch = "2">
.
.
.
.
<params amount = n code = n batch = n>(based on length of above array)
</delta>
<keys number = "02154029" name = "Allen">
<keys number= "92154429" name = "Peter">
.
.
.
<keys number= n name = n >(based on length of above array)
</request>
I request you to help me on this, by creating a logic using Javascript
Please let me know for any clarifications
It's a little complicated, given your expected output, but doable, using a template, json parser, DOMParser and querySelector:
tmpl = `<doc>
<request>
<delta>
</delta>
</request>
</doc>`
const data = `[{
"JK": true,
"Number": "02154029",
"Name": "Allen",
"Type": "Delta",
"Code": "ASM",
"Amount": 10
},
{
"JK": true,
"Number": "92154429",
"Name": "Peter",
"Type": "Delta",
"Code": "FLSM",
"Amount": 50
}
]`
const jdata = JSON.parse(data);
const xmldoc = new DOMParser().parseFromString(
tmpl,
'text/xml'
);
dest = xmldoc.querySelector('delta')
counter = 1;
for (let jd of jdata){
dest.insertAdjacentHTML(
'beforeend',
`<lineItem id = "${counter}"> </lineItem>
`
);
counter++;
}
for (let jd of jdata){
dest.insertAdjacentHTML(
'beforeend',
`<params amount = "${jd.Amount}" code = "${jd.Code}"> </params>
`
);
}
for (let jd of jdata){
dest.insertAdjacentHTML(
'afterend',
`
<keys number = "${jd.Number}" name = "${jd.Name}"> </keys>
`
);
}
alert(xmldoc.documentElement.innerHTML)