Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML to JSON - dealing with xml namespaces and alias in JavaScript

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?

like image 478
Travis Nelson Avatar asked Jun 29 '12 16:06

Travis Nelson


Video Answer


1 Answers

For those who use typescript

  • add this import statement (you will need npm install -D @types/xml2js)
import { Parser, processors } from 'xml2js';
  • add tagNameProcessor option when create a new parser
    const parser = new Parser(
        {  
            trim: true,  
            explicitArray: false,
            tagNameProcessors: [processors.stripPrefix]
        });
        parser.parseString(xmlData, function(err, result)
        { 
like image 86
Pavel Popov Avatar answered Sep 23 '22 02:09

Pavel Popov