Created
November 5, 2010 20:27
Fetches a XML file and iterates of price elements - node.js + jquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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