X

Geertjan's Blog

  • January 3, 2016

Reading XML in Oracle JET

Geertjan Wielenga
Product Manager

There's an interesting question on the Oracle JET forum about reading an XML file into an Oracle JET application. The person asking the question is using a 'require' block, whereas below I'm using a 'define' block, since the code below is in a custom Oracle JET module, since Oracle JET is perfect for creating modular JavaScript applications.

Here's the JavaScript side...

define(['ojs/ojcore', 'knockout', 'ojs/ojtable'
], function (oj, ko) {
function mainContentViewModel() {
var self = this;
var deptObservableArray = ko.observableArray([]);
self.datasource = new oj.ArrayTableDataSource(deptObservableArray, {idAttribute: 'id'});
self.addData = function () {
$.ajax({
url: "cd_catalog.xml",
type: 'GET',
dataType: 'xml',
success: function (data, textStatus, jqXHR) {
var x = data.getElementsByTagName("CD");
for (i = 0; i < x.length; i++) {
l_artist = x[i].getElementsByTagName("ARTIST")[0].
childNodes[0].nodeValue;
l_title = x[i].getElementsByTagName("TITLE")[0].
childNodes[0].nodeValue;
deptObservableArray.push({
id: i,
artist: l_artist,
title: l_title});
}
}
});
};
//Maybe call the function from the 'click' binding of a button,
//but for the moment let's just call it automatically:
self.addData();
};
return mainContentViewModel;
});

And here's the HTML side, which is identical to how it is in the questioner's post in the forum:

<table id="table2" summary="Album List" aria-label="Album Table"
data-bind="ojComponent: {component: 'ojTable',
data: datasource,
columnsDefault: {sortable: 'none'},
columns: [{headerText: 'Id',
field: 'id'},
{headerText: 'Artist',
field: 'artist'},
{headerText: 'Title',
field: 'title'}]}">
</table>

Make sure your XML file is in the 'public_html' folder, as shown below, and everything will work as you'd expect:

Also it's a good idea to watch this recent YouTube screencast by JB Brock, though he uses JSON, not XML, as in the example above. I can now see this in the browser:

The XML file comes from here: http://www.w3schools.com/xml/cd_catalog.xml

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.