Parse XML properties to JS
Takes and array of strings representing properties of objects being passed and
returns objects with those properties parsed from XML to JSON:
var ncbi = require('bionode-ncbi')
var tool = require('tool-stream')
var searchStream = ncbi.search('sra', 'solenopsis invicta')
var parseStream = tool.XMLToJSProperties(['expxml', 'runs'])
searchStream.pipe(parseStream).on('data', console.log)
=> { uid: '225471',
expxml:
{ root:
{ Summary: [Object],
Submitter: [Object],
Experiment: [Object],
Study: [Object],
Organism: [Object],
Sample: [Object],
Instrument: [Object],
Library_descriptor: [Object],
Biosample: [Object],
Bioproject: [Object] } },
runs: { root: { Run: [Object] } },
extlinks: ' ',
createdate: '2013/03/28',
updatedate: '2013/09/23' }
[...]
ToolStream.prototype.XMLToJSProperties = function(properties) {
return through.obj(parser)
function parser(obj, enc, next) {
var self = this
async.forEach(properties, parseXMLProperty, gotAllParsed)
function gotAllParsed(err) {
if (err) { return self.emit('error', err) }
self.push(obj)
next()
}
function parseXMLProperty(property, callback) {
parseXMLString(obj[property], gotPropertyParsed)
function gotPropertyParsed(js){
obj[property] = js
callback()
}
}
}
function parseXMLString(xmlString, callback) {
var xml = '<root>'
+ xmlString
.replace(/</g, '<')
.replace(/>/g, '>')
+ '</root>'
xml2js(xml, gotStringParsed)
function gotStringParsed(err, js) {
if (err) { return self.emit('error', err) }
callback(js)
}
}
}