Android - XPath evaluates very slowly

I use XPath to query my XML-file , which currently has about 100KB .

I repeat the array and query for each value in the list.

Unfortunately, a single request takes about 3-4 seconds under the debugger and is slightly less with the debugger disabled.

Any ideas why this is so slow? I use Galaxy S2 for testing.

Here is my code:

 XPath xpath = XPathFactory.newInstance().newXPath(); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document document = builder.parse(new File(file_on_internal_sd_url))); int size = mPrefs.getInt("no_ids", 0); for(int i=0;i<size;i++) { String id= mPrefs.getString("id_" + i, null); String expression = "/tag1/tag2[@id = '" + id+ "']"; NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET); if(nodes.getLength()>0) { myElements.add((Element)nodes.item(0)); } } 

Update

When I omit XPathConstants.NODESET , evaluation is done as soon as possible, but I do not get NodeList . Instead, it returns an empty string ...

+2
source share
2 answers

Thanks to @nvrmnd, I did a little work and found a better parser:

VTD-XML

Here is an example from the developers.

But this tutorial is better ...

Hope this helps anyone who was as upset as I was ...

+2
source

XPath itself is not very efficient when it comes to iterating through large XML documents. I myself made the experience that it took about 10 seconds to parse the values ​​from ~ 200 kb of the XML file on the younger device.

After that, I redefined the parser as SAXParser and had a huge performance increase of about 2 orders of magnitude. Therefore, I suggest you try SAXParser. In fact, this is not so difficult to implement, and there are several tutorials.

There is also a stackoverflow question that addresses the topic of various parsing methods: SAX vs. DOM vs. XPath

I also assume that evaluation is done as soon as possible when you are not using NodeSet, because it will search for only one node and return as soon as it finds the corresponding node.

EDIT:

Parsing an XML document with SAX means that you iterate over it and store the information you need in objects. Take a look at this tutorial: SAX Tutorial

There, the author parses information about the staff and converts it into objects, so I think that is exactly what you need.

+1
source

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


All Articles