UNPKG

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