Skip to content

Instantly share code, notes, and snippets.

Created November 5, 2010 20:27
Show Gist options
  • Save anonymous/664739 to your computer and use it in GitHub Desktop.
Save anonymous/664739 to your computer and use it in GitHub Desktop.
Fetches a XML file and iterates of price elements - node.js + jquery
var fs = require('fs'), util = require('util'),
jsdom = require('jsdom'), http = require('http');
var jQueryHome = '/home/woidda/libs/js/jquery-1.4.2.min.js';
var xmlFileUrl = 'http://www.w3schools.com/xml/plant_catalog.xml';
var host = 'www.w3schools.com';
var client = http.createClient(80, host);
var request = client.request('GET', xmlFileUrl,
{'host': 'www.w3schools.com'});
request.on('response', function (response) {
response.setEncoding('utf8');
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function(){
var window = jsdom.jsdom().createWindow();
jsdom.jQueryify(window, jQueryHome, function () {
var sumOffPrices = 0;
window.jQuery(body).find('PRICE').each(function () {
var priceString = window.jQuery(this).text();
var price = parseFloat(priceString.substr(1, priceString.length));
sumOffPrices += price;
});
console.log(sumOffPrices);
});
});
});
request.end();
// file based version - store the xml file in the folder with the script or alter path accordingly
/*
fs.readFile('plant_catalog.xml', 'UTF-8', function(err, chunk){
if(err) throw err;
var window = jsdom.jsdom().createWindow();
jsdom.jQueryify(window, jQueryHome, function () {
var sumOffPrices = 0;
window.jQuery(chunk).find('PRICE').each(function () {
var priceString = window.jQuery(this).text();
var price = parseFloat(priceString.substr(1, priceString.length));
sumOffPrices += price;
});
console.log(sumOffPrices);
});
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment