The fastest way to parse this XML in JS

Let's 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 am currently using this to get the name of each book:

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

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

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

I find it very slow when the books are really big. Unfortunately, there is no way to limit the result set and not specify a different return type.

Is there a faster way?

+3
source share
2 answers

XMLHttpRequest, XML responseXML (.. XML DOM). , , , javascript UA.

XML, XPath:

Mozilla

MSDN

XPath (, //parentNode/node/text()) 134 , node 439 , ( , evalXPath()), , nodeValue node , , alert() join('\n'). 3 .

487 529 4 (IE 6 15 , ). , , , XML-, XPath script .

+5

XML- XML JSON, JS . .

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

// when a tag has attributes
var options = {
        attrPrefix : "@_",
        textNodeName : "#text",
        ignoreNonTextNodeAttr : true,
        ignoreTextNodeAttr : true,
        ignoreNameSpace : true
    };
var jsonObj = fastXmlParser.parse(xmlData,options);

//Intermediate obj
var tObj = fastXmlParser.getTraversalObj(xmlData,options);
var jsonObj = fastXmlParser.convertToJson(tObj);

npm, parser.js HTML.

0

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


All Articles