Android - XPath evaluate very slow

2020-03-27 16:21发布

I'm using XPath to query my XML-file which has at the moment about 100KB.

I'm iterating of an array and query for every value in the list.

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

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

Here's 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 leave out the XPathConstants.NODESET the evalution is done in no time but I don't get a NodeList. It returns an empty string instead...

2条回答
我只想做你的唯一
2楼-- · 2020-03-27 16:58

XPath itself is not very efficient when it comes to iterating through big XML-documents. I myself made the experience that parsing values out of a ~200kb XML-file took around 10 seconds on a low-end device.

After that I reimplemented the parser as a SAXParser and had huge performance increases of around 2 orders of magnitude. So I would propose that you try the SAXParser. It is actually not too hard to implement and there are a couple of tutorials out there.

There also exists a question on stackoverflow that deals with the topic of the various parsing methods: SAX vs. DOM vs. XPath

I also assume that the evaluation is done in no time when you don't use NodeSet because it will only look for a single node and return as soon as it has found a matching node.

EDIT:

Parsing the XML-document with SAX means that you iterate through it and store the sought information within objects. Take a look at this tutorial: SAX Tutorial

There the author parses staff information and transforms it into objects so I guess that's exactly what you need.

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-03-27 17:03

Thanks to @nvrmnd I tried a bit around and found a way better parser:

VTD-XML

Here's a example from the devlopers.

But this Tutorial is way better...

Hope this helps anyone being as frustrated as I was...

查看更多
登录 后发表回答