I am trying to convert XML to JSON in node.js using the xml2js module. How to handle namespace alias when accessing variables?
The following code converts my file (sampleWithNamespaces.xml)
var fs = require('fs'), xml2js = require('xml2js'); var parser = new xml2js.Parser(); fs.readFile('sampleWithNamespaces.xml', function (err, data) { parser.parseString(data, function (err, result) { console.dir(result); console.log('Done'); }); });
sampleWithNamespaces.xml:
<d:student xmlns:d='http://www.develop.com/student'> <d:id>3235329</d:id> <d:name>Jeff Smith</d:name> <d:language>JavaScript</d:language> <d:rating>9.5</d:rating> </d:student>
Conclusion:
$ node xml2jsTest.js { '@': { 'xmlns:d': 'http://www.develop.com/student' }, 'd:id': '3235329', 'd:name': 'Jeff Smith', 'd:language': 'JavaScript', 'd:rating': '9.5' } Done
I can access the 'name' attribute using the result['d:name']
result.name
instead of result.name
if I didn't have a namespace alias. To my question, am I doing this correctly?
I read : “If an element has a namespace alias, the alias and element are combined using“ $. For example, the ns: element element becomes ns $ element. ”If I do this, I can read the attribute as result.d$name
. If I went along this route, how would I succeed?
source share