Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  169] [ 4]  / answers: 1 / hits: 17843  / 14 Years ago, mon, february 28, 2011, 12:00:00

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?


More From » xml

 Answers
12

Presumably you are using XMLHttpRequest, in which case the XML is parsed before you call any methods of responseXML (i.e. the XML has already been parsed and turned into a DOM). If you want a faster parser, you'll probably need a different user agent or a different javascript engine for your current UA.



If you want a faster way to access content in the XML document, consider XPath:



Mozilla documentation



MSDN documentation



I used an XPath expression (like //parentNode/node/text()) on a 134KB local file to extract the text node of 439 elements, put those into an array (because that's what my standard evalXPath() function does), then iterate over that array to put the nodeValue for each text node into another array, doing two replace calls with regular expressions to format the text, then alert() that to the screen with join('n'). It took 3ms.



A 487KB file with 529 nodes took 4ms (IE 6 reported 15ms but its clock has very poor resolution). Of course my network latency will be nearly zero, but it shows that the XML parser, XPath evaluator and script in general can process that size file quickly.


[#93547] Friday, February 25, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zaynerogerb

Total Points: 454
Total Questions: 109
Total Answers: 97

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;