XML for JSON - working with xml namespaces and aliases in JavaScript

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?

+6
source share
3 answers

I had a similar problem. Most of my XML tags were in the same namespace. So I decided to remove all namespaces from my XML.

You can split namespaces when parsing XML by adding tagNameProcessors in xml2js .

 var parseString = require('xml2js').parseString; var stripNS = require('xml2js').processors.stripPrefix; parseString(xml_str, { tagNameProcessors: [stripNS] },function(err, result) {}); 

This will ignore the entire namespace. If you have XML tags from multiple namespaces, this may not be very useful.

+2
source

The document you are quoting has nothing to do with xml2js, but you can get the same template if you want. You will have to change the xml2js source code or the loop, renaming everything after loading, both of which are not great ideas (the first means you won’t be able to upgrade so easily, and both will add overhead to your code), so you should just stick to the syntax [ 'd: name']. The only drawback is that it adds 3 characters to each search, but if your server uses gzip, it will not make any difference in the real world.

If you really want to, this function will rename everything:

 function colonToDollar(obj){ var r={}; for(var k in obj){ r[k.replace(/:/g,'$')] = (typeof obj[k]==='object') ? colonToDollar(obj[k]) : obj[k]; } return r; } 
0
source

if you use node and xml2js, use result["ns:entry"] to refer to a specific entry

0
source

Source: https://habr.com/ru/post/919344/


All Articles