Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest Way to Parse this XML in JS

Say I have this XML with about 1000+ bookinfo nodes.

<results>
  <books>
   <bookinfo>
        <name>1</dbname>
   </bookinfo>
   <bookinfo>
     <name>2</dbname>
   </bookinfo>
   <bookinfo>
     <name>3</dbname>
   </bookinfo>
 </books>
</results>

I'm currently using this to get the name of each book:

var books = this.req.responseXML.getElementsByTagName("books")[0].getElementsByTagName("bookinfo")

Then use a for loop to do something with each book name:

var bookName = books[i].getElementsByTagName("name")[0].firstChild.nodeValue;

I'm finding this really slow when books is really big. Unfortunately, there's no way to limit the result set nor specify a different return type.

Is there a faster way?

like image 451
doremi Avatar asked Dec 04 '22 09:12

doremi


1 Answers

You can try fast xml parser to convert XML data to JSON which is implemented in JS. Here is the benchmark against other parser.

var parser = require('fast-xml-parser');
var jsonObj = parser.parse(xmlData);

// when a tag has attributes
var options = {
        attrPrefix : "@_"        };
var jsonObj = parser.parse(xmlData,options);

If you don't want to use npm library, you can include parser.js in your HTML directly.

Disclaimer: I'm the author of this library.

like image 188
Amit Kumar Gupta Avatar answered Dec 26 '22 14:12

Amit Kumar Gupta