0

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.

2
  • Could you edit your question and add the looping code you already have as minimal reproducible example? Commented Jul 26, 2021 at 10:36
  • @shaedrich Sure, I am on it. Thanks Commented Jul 26, 2021 at 10:38

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Appreciate your time. Updated the question. Need the function to be dynamic. Added the one with which I tried, pls check. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.