Reputation: 473
I want to extract all the data from the XML which has text nodes that is present in a variable and create an object array. Using Jquery for the same.
I have the below XML data.
var header = ['name', 'data1', 'data2'];
var data = '<parent1>' +
'<person>' +
'<name>Name1</name>' +
'<details>' +
'<data1>123</data1>' +
'<data2>34567</data2>' +
'</details>' + '</child>' + '<person>' +
'<name>Name1</name>' +
'<details>' +
'<data1>123</data1>' +
'<data2>34567</data2>' +
'</details>' + '<person>' + '</parent1>';
xmlDoc = $.parseXML( data ),
$xml = $( xmlDoc ),
var tabData = [];
var obj = {};
$xml.find('parent1').each(function(item, index){
header.forEach(function (item, index) {
$t = $xml.find(item).text();
obj[item] = $t;
});
tabData.push(obj);
obj = {};
The object should contain
{name : Name1, data1 :123, data2:34567}, {name : Name2, data1 :123, data2:34567}.
The loop is not having the access to the textnodes. $this does not help me get the search done for the individual child as well.
Requirement is the function should be dynamic and should work any type of the XML trees.
Could anyone please help.
Upvotes: 0
Views: 86
Reputation: 597
You can loop over the xml using parseXML
. You did have a few errors in your XML data so double check you have the correct closing XML tags before you continue.
Loop through each person XML element and create a javascript obj then push it into an array.
See example below:
var xml = '<parent1><person><child><name>Name1</name><details><data1>123</data1><data2>34567</data2></details></child></person><person><child><name>Name2</name><details><data1>123</data1><data2>34567</data2></details></child></person></parent1>';
var xmlDoc = $.parseXML(xml);
var $xml = $(xmlDoc);
var array = [];
$xml.find('person').each(function (index) {
var obj = {
name: $(this).find('name').text(),
data1: $(this).find('data1').text(),
data2: $(this).find('data2').text()
};
array.push(obj);
});
console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Upvotes: 1