Reputation: 355
I have the below xml and i need to form it in javascript,
<?xml version="1.0" encoding="UTF-8" ?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<empNum>00206502</empNum>
<itemlist>
<orderid>4314</orderid>
<transactiondttm>2014-01-15</transactiondttm>
</itemlist>
<itemlist>
<orderid>413</orderid>
<transactiondttm>2014-01-15</transactiondttm>
</itemlist>
</Employee>
and the number itemlist node has to be generated dynamically? Any idea how it can be done.
Upvotes: 0
Views: 69
Reputation: 601
To form xml dynamically :
<script>
// Simple helper function creates a new element from a name, so you don't have to add the brackets etc.
$.createElement = function (name) {
return $('<' + name + ' />');
};
// JQ plugin appends a new element created from 'name' to each matched element.
$.fn.appendNewElement = function (name) {
this.each(function (i) {
$(this).append('<' + name + ' />');
});
return this;
}
/* xml root element - because html() does not include the root element and we want to
* include <Employee /> in the output. There may be a better way to do this.
*/
var $root = $('<XMLDocument />');
$root.append
(
// one method of adding a basic structure
$('<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>').append
(
$('<empNum />').text('1') //pass employee no
)
);
// get a reference to Employee
var $Employee = $root.find('Employee');
// get a reference to itemlist
// or find itemlist from the $root like this: $root.find('Employee>itemlist');
var list = { id1: 'transactiondttm1', id2: 'transactiondttm2', id3: 'transactiondttm3', id4: 'transactiondttm4' }; // array with values
$.each(list, function (a, b) {
// create 'Alice'
var $newitemlist = $.createElement('itemlist');
// add 'orderid' element using standard jQuery
$newitemlist.append($('<orderid />').text(a));
// add 'transactiondttm' element using our helper
$newitemlist.append($.createElement('transactiondttm').text(b));
// add 'Alice' to <itemlist />
$Employee.append($newitemlist);
}
);
// display the markup as text
alert($root.html());
document.write($root.html());
</script>
This is how you can generate xml in javascript/jquery Please try this and you will see output as
<?xml version="1.0" encoding="UTF-8"?>
<employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<empnum>1</empnum>
<itemlist>
<orderid>id1</orderid>
<transactiondttm>transactiondttm1</transactiondttm>
</itemlist>
<itemlist>
<orderid>id2</orderid>
<transactiondttm>transactiondttm2</transactiondttm>
</itemlist>
<itemlist>
<orderid>id3</orderid>
<transactiondttm>transactiondttm3</transactiondttm>
</itemlist>
<itemlist>
<orderid>id4</orderid>
<transactiondttm>transactiondttm4</transactiondttm>
</itemlist>
</employee>
Hope this helps you, if Any queries feel free to ask questions :)
Upvotes: 1