get-products.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // pull out /GeneralSearchResponse/categories/category/items/product tags
  2. // the rest we don't care about.
  3. var sax = require("../lib/sax.js")
  4. var fs = require("fs")
  5. var path = require("path")
  6. var xmlFile = path.resolve(__dirname, "shopping.xml")
  7. var util = require("util")
  8. var http = require("http")
  9. fs.readFile(xmlFile, function (er, d) {
  10. http.createServer(function (req, res) {
  11. if (er) throw er
  12. var xmlstr = d.toString("utf8")
  13. var parser = sax.parser(true)
  14. var products = []
  15. var product = null
  16. var currentTag = null
  17. parser.onclosetag = function (tagName) {
  18. if (tagName === "product") {
  19. products.push(product)
  20. currentTag = product = null
  21. return
  22. }
  23. if (currentTag && currentTag.parent) {
  24. var p = currentTag.parent
  25. delete currentTag.parent
  26. currentTag = p
  27. }
  28. }
  29. parser.onopentag = function (tag) {
  30. if (tag.name !== "product" && !product) return
  31. if (tag.name === "product") {
  32. product = tag
  33. }
  34. tag.parent = currentTag
  35. tag.children = []
  36. tag.parent && tag.parent.children.push(tag)
  37. currentTag = tag
  38. }
  39. parser.ontext = function (text) {
  40. if (currentTag) currentTag.children.push(text)
  41. }
  42. parser.onend = function () {
  43. var out = util.inspect(products, false, 3, true)
  44. res.writeHead(200, {"content-type":"application/json"})
  45. res.end("{\"ok\":true}")
  46. // res.end(JSON.stringify(products))
  47. }
  48. parser.write(xmlstr).end()
  49. }).listen(1337)
  50. })