Loop through XML nodes and store as JavaScript variables - javascript

I am new to JavaScript and I am trying to read an XML file and extract its content into JavaScript variables.
Here is an example of the content of my XML file:
<!-- Locations of current projects -->
<projectsites>
<li>
<title>Battling Ninja Army</title>
<location>Osaka, Japan</location>
<lat>34.69</lat>
<lon>135.50</lon>
</li>
<li>
<title>Software Development</title>
<location>Vienna, Austria</location>
<lat>48.21</lat>
<lon>16.37</lon>
</li>
</projectsites>
<!-- Locations of current developers -->
<developersites>
<li>
<title>Brisbane office</title>
<location>Brisbane, Australia</location>
<lat>-27.4</lat>
<lon>153</lon>
</li>
<li>
<title>Phillipines Office</title>
<location>Manilla, Phillipines</location>
<lat>14.7</lat>
<lon>121</lon>
</li>
</developersites>
So, presuming that I have more data than this, can I create a loop or nested loops in JavaScript that reads the XML file and extracts the data into arrays? Examples of elements that I am interested in are: projectsites.title, projectsites.lat, developersites.title and developersites.lat.

using jQuery to parse the xml, here's my implementation of a function that converts the xml to a json :
function xmlToObject(xml) {
if (xml instanceof jQuery) xml = xml.get(0);
var o = {};
function level(node, obj) {
obj[node.nodeName] = {};
$.each(node.attributes, function (i, attr) {
obj[node.nodeName][attr.name] = attr.value;
});
$(node).children().each(function (i, child) {
level(child, obj[node.nodeName]);
});
}
if (xml.nodeName === '#document' || xml.nodeName === 'document')
$(xml).children().each(function (i, child) {
level(child, o);
});
else
level(xml, o);
return o;
};

You can use jQuery to easily get xml data and parse it. Here is an example:
var projectsite_titles = [];
$.get('myXmlFile.xml', function(responseXml) {
$(responseXml).find('projectsites li title').each(function () {
projectsite_titles.push($(this).text());
});
}, 'xml');

Related

javascript append from foreach loop not working

I am writing simple changelog for my website that uses github api and appends tag but it doesnt work.
this is my code:
<p id="testing"></p>
<script>
var c = document.getElementById("testing");
$.getJSON("https://api.github.com/repos/test234/test/releases").done(function (json) {
for each (release in json) {
c.appendChild(document.createTextNode(release.tag_name));
}
});
</script>
I think something is wrong with my foreach loop.
Any help is welcome I am stuck here for a long time
This is the right way to use forEach:
var c = document.getElementById("testing");
$.getJSON("https://api.github.com/repos/4u7157/DOWNLOADS/releases").done(function (json) {
json.forEach((e) => {
console.log(e);
c.appendChild(document.createTextNode(e.tag_name));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="testing"></p>
You can also use JQuery as follows:
var c = document.getElementById("testing");
$.getJSON("https://api.github.com/repos/4u7157/DOWNLOADS/releases").done(function (json) {
$.each(json, function( index, e ){
console.log(e);
c.appendChild(document.createTextNode(e.tag_name));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="testing"></p>
well, the reason is that your syntax is appropriate for arrays but here json is object so this syntax will not work unless you use Object.Entries
const entries = Object.entries(json)
for(const [index,obj] of entries){
c.appendChild(document.createTextNode(obj.tag_name))
}
or you can use for each method provided for objects like this :
json.forEach(function(value,key,obj){
c.appendChild(document.createTextNode(value.tag_name))
});
Rest is all good , you just need to look for these changes.

Handlebars: 2 sources 1 template

I have one handlebars template but I want to include variables from two different sources in this template.
<script id="notification-menu-item" type="text/x-handlebars-template">
I have tried to make both of the sources go to the same template id. Both files have this:
var source = $("#notification-menu-item").html();
var template = Handlebars.compile(source);
But only one of sources' variable come through to the template. Is there anyway to have one template get its {{variables}} from two different sources?
Edit: The code
This is the template:
<script id="notification-menu-item" type="text/x-handlebars-template">
<div id="navmenucontainer" class="container">
<div id="navmenuv">
<ul class="nav">
<li>Topics</li>
<li>Help</li>
{{#if logged_user}}
<li>Notifications</li>
{{#if pro}}
<li>My Data</li>
{{/if}}
{{/if}}
</ul>
</div>
</div>
</script>
pro comes from one .js file and logged_user comes from a separate .js file. Is there a way for both of these variable to be used in the same template?
You'll have to centralize the rendering of the template into one function somehow if you want to composite the data before passing it into the Handlebars.compile() function. I guess you're going to have to somehow guarantee the order in which these "plugin" js files call this new function. Otherwise it turns into something really janky like this:
Example:
Class1.js
var source = $("#notification-menu-item").html();
var html = Notification.renderNotification(source, logged_user, undefined);
if (typeof html !== 'undefined') {
$('body').prepend(html);
}
Class2.js
var source = $("#notification-menu-item").html();
var html = Notification.renderNotification(source, undefined, pro);
if (typeof html !== 'undefined') {
$('body').prepend(html);
}
Notification.js
window.Notification = function() {
var logged_user = undefined;
var pro = undefined;
return {
renderNotification: function(source, user, isPro) {
if (typeof user !== 'undefined') {
logged_user = user;
}
if (typeof pro !== 'undefined') {
pro = isPro;
}
if(typeof logged_user !== 'undefined'
&& typeof pro !== 'undefined') {
var template = Handlebars.compile(source);
var html = template({logged_user: logged_user, pro: pro});
return html;
}
}
}
Obviously this is not elegant and far from maintainable. Without getting into the specifics of how Discourse works though, I'm not sure what to tell you. At render time of the template, a full object containing all the relevant data should be passed. Subsequent calls to Handlebars.compile() would require the full set of data. Maybe should consider finding a way to split these templates up and render them into separate page elements asynchronously, or look into Partials
Disclaimer: I'm not an expert on JS or logicless templates.

How to create html list from a json file (handlebars)

I have an empty todo list:
<ul class="list">
</ul>
I want to create a li inside that list for each json title I have in the following json data:
[{"id":2,"title":"Mandar cartas a impresión","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:09:55.552Z","updated_at":"2015-12-07T13:09:55.552Z","project_id":1},{"id":3,"title":"CIF Intracomunitario","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:10:05.736Z","updated_at":"2015-12-07T13:10:05.736Z","project_id":1},{"id":4,"title":"Uniformes Chef a Porter","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:10:16.170Z","updated_at":"2015-12-07T13:10:16.170Z","project_id":1},{"id":5,"title":"Personal","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:10:31.569Z","updated_at":"2015-12-07T13:10:31.569Z","project_id":1},{"id":1,"title":"Mandar contrato pleni","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:09:36.747Z","updated_at":"2015-12-07T13:13:12.068Z","project_id":1},{"id":17,"title":"Comprar TPV","description":"","status":false,"priority":null,"created_at":"2015-12-08T00:18:40.753Z","updated_at":"2015-12-08T00:18:40.753Z","project_id":1},{"id":18,"title":"Vajillas Zara Home","description":"","status":false,"priority":null,"created_at":"2015-12-08T00:18:54.580Z","updated_at":"2015-12-08T00:18:54.580Z","project_id":1},{"id":19,"title":"Tpv","description":"","status":false,"priority":null,"created_at":"2015-12-08T00:33:17.393Z","updated_at":"2015-12-08T00:33:17.393Z","project_id":1},{"id":21,"title":"Wifi - Contratar","description":"","status":false,"priority":null,"created_at":"2015-12-08T15:33:24.639Z","updated_at":"2015-12-08T15:33:24.639Z","project_id":1},{"id":22,"title":"Cuenta Definitiva Santander","description":"","status":false,"priority":null,"created_at":"2015-12-08T15:33:50.255Z","updated_at":"2015-12-08T15:33:50.255Z","project_id":1},{"id":23,"title":"Pagarés Kider","description":"","status":false,"priority":null,"created_at":"2015-12-08T15:34:08.162Z","updated_at":"2015-12-08T15:34:08.162Z","project_id":1}]
So, I have the following javascript which uses handlebars for templating:
<script>
jQuery.getJSON("http://myurl/tasks.json", function(data){
var source = $("#tasks-template").html();
var template = Handlebars.compile(source);
$.each(data) function() {
var context = data;
var show = template(context);
$(".list").html(show);
});
});
</script>
My handlebars template:
<script id="tasks-template" type="text/x-handlebars-template">
<li>
<div>{{title}}</div>
</li>
</script>
It wont create a li in my html for each title in the json.
What am I missing?
Thanks!
When you iterate for each object of the array received in the JSON, you have to use this instead of data to access to the object.
data is the whole array and this is the current object where you want to retrieve the title property:
$.each(data, function() {
var context = this;
var show = template(context);
$(".list").append(show);
});
And also change the html method for append for don't overwrite the content.
Regards

Handlebars.js group by value

I'm using Handlebars to display some datas via ajax, and the JSON is like this:
{"data":[
{ "sn":"43","areasn":"3","name":"X1","status":"empty","seats":"12"},
{ "sn":"22","areasn":"1","name":"F1","status":"empty","seats":"8"},
{ "sn":"12","areasn":"2","name":"E1","status":"empty","seats":"6"},
{ "sn":"18","areasn":"3","name":"R3","status":"empty","seats":"6"},
{ "sn":"31","areasn":"1","name":"G4","status":"empty","seats":"4"},
{ "sn":"23","areasn":"2","name":"W5","status":"empty","seats":"12"}
]}
and I need to use handlebars.js in order to display tables in differents areas, something like these:
<script id="tables-template" type="text/x-handlebars-template">
{{#each data}}
// All tables in area-1
<ul id="area-{{areasn}}">
<li id="{{sn}}">{{name}}</li>
</ul>
// All tables in area-2
<ul id="area-{{areasn}}">
<li id="{{sn}}">{{name}}</li>
</ul>
// All tables in area-3
<ul id="area-{{areasn}}">
<li id="{{sn}}">{{name}}</li>
</ul>
{{/each}}
</script>
I have no idea how to write a helper for this, is anyone can help? thanks!
There is probably a better way of doing this as I don't know about handlebars, but this should do what you are looking for:
(function() {
var id = 0,
cache = [];
var ids={};
Handlebars.registerHelper("groupData", function(data) {
var dataKey = id++;
ids[data.areasn]=true;
if(cache[data.areasn]==undefined) cache[data.areasn]={id:data.areasn, data:[data]};
else cache[data.areasn].data.push(data)
if(dataKey==context.data.length-1){
context.cache=[];
for(var i in ids){
context.cache.push(cache[i])
}
}
});
})();
var context={"data":[
{ "sn":"43","areasn":"3","name":"X1","status":"empty","seats":"12"},
{ "sn":"22","areasn":"1","name":"F1","status":"empty","seats":"8"},
{ "sn":"12","areasn":"2","name":"E1","status":"empty","seats":"6"},
{ "sn":"18","areasn":"3","name":"R3","status":"empty","seats":"6"},
{ "sn":"31","areasn":"1","name":"G4","status":"empty","seats":"4"},
{ "sn":"23","areasn":"2","name":"W5","status":"empty","seats":"12"}
]}
var template = Handlebars.compile($("#your-template").text());
var html = template(context);
document.body.innerHTML=html;
Check fiddle for html:
http://jsfiddle.net/mE49M/226/

Extracting value from JSON generated source code on a page

I have the below JSON data that is present in the source of our product detail pages (this is an ecommerce site).
I need to pull the "atrsell" value from each line using javascript/jquery.
Can somebody give me the bext way to do this please?
<script type="text/javascript">
$(document).ready(function(){
Attributes.StoreJSON({"att1":"Cobalt","att3":"","att2":"6","att4":""},{"atronhand":24,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"6","atrsku":"505274940925","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"30.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Cobalt","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Cobalt","att3":"","att2":"8","att4":""},{"atronhand":3430,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"8","atrsku":"505274940926","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"30.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Cobalt","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Cobalt","att3":"","att2":"14","att4":""},{"atronhand":50,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"14","atrsku":"505274940922","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"30.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Cobalt","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"12","att4":""},{"atronhand":3,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"12","atrsku":"505274940942","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"14","att4":""},{"atronhand":1,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"14","atrsku":"505274940943","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"16","att4":""},{"atronhand":322,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"16","atrsku":"505274940944","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"18","att4":""},{"atronhand":200,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"18","atrsku":"505274940945","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Navy","att3":"","att2":"10","att4":""},{"atronhand":431,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"10","atrsku":"505274940927","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"10.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Navy","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Phantom","att3":"","att2":"10","att4":""},{"atronhand":3443,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"10","atrsku":"505274940913","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"20.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Phantom","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Phantom","att3":"","att2":"12","att4":""},{"atronhand":99,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"12","atrsku":"505274940914","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"20.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Phantom","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Sweet Grape","att3":"","att2":"16","att4":""},{"atronhand":433,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"16","atrsku":"505274944584","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"68.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Sweet Grape","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Sweet Grape","att3":"","att2":"18","att4":""},{"atronhand":20,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"18","atrsku":"505274944585","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"68.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Sweet Grape","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
});
</script>
Try
var arr = [],
Attributes = {
StoreJSON: function(obj1, obj2) {
arr.push(obj2);
}
};
/* Your code here*/
var atrsells = arr.map(function(i){
return i.atrsell;
});

Categories

Resources