Skip to content

Instantly share code, notes, and snippets.

@isaacs
Created October 21, 2011 23:14
Show Gist options
  • Select an option

  • Save isaacs/1305238 to your computer and use it in GitHub Desktop.

Select an option

Save isaacs/1305238 to your computer and use it in GitHub Desktop.
// pull out /GeneralSearchResponse/categories/category/items/product tags
// the rest we don't care about.
var sax = require("../lib/sax.js")
var fs = require("fs")
var path = require("path")
var xmlFile = path.resolve(__dirname, "shopping.xml")
var xmlstr = fs.readFileSync(xmlFile).toString()
var parser = sax.parser(true)
var products = []
var product = null
var currentTag = null
parser.onclosetag = function (tagName) {
if (tagName === "product") {
products.push(product)
currentTag = product = null
return
}
currentTag = currentTag && currentTag.parent
}
parser.onopentag = function (tag) {
if (tag.name !== "product" && !product) return
if (tag.name === "product") {
product = tag
}
tag.parent = currentTag
tag.children = []
tag.parent && tag.parent.children.push(tag)
currentTag = tag
}
parser.ontext = function (text) {
if (currentTag) currentTag.children.push(text)
}
parser.onend = function () {
var util = require("util")
var out = util.inspect(products, false, Infinity, true)
console.error(out)
}
parser.write(xmlstr).end()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment