I am trying to convert XML to JSON in node.js using the module xml2js. How do I handle the namespace alias when accessing variables?
The follow 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>
Output:
$ 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 by using the notation result['d:name']
instead of result.name
if I did not have the namespace alias. I guess my question is, am I doing this the right way?
I've read that "If an element has a namespace alias, the alias and element are concatenated using "$". For example, ns:element becomes ns$element" If I do this I can read the attribute as result.d$name
. If I went this route, how would I got about doing so?
For those who use typescript
import { Parser, processors } from 'xml2js';
const parser = new Parser(
{
trim: true,
explicitArray: false,
tagNameProcessors: [processors.stripPrefix]
});
parser.parseString(xmlData, function(err, result)
{
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With