Search code examples
javaxmlxpathvtd-xml

Xpath and VTD-XML, getting the node index


I'm using VTD-XML to parse some XML files with Xpath expressions, now following showed up: I need to know the index of a node from the xml tree, after a bit of searching I found that a expression like this

count(//ds[name='cpu1']/preceding-sibling::*)+1

Provides me the needed index - my question is: As far I'm using VTD-XML (because its fast) is there a possibility to use this kind of expression within VTD-XML? Using the given expression causes just a XpathParseException.

My xml look like this:

<?xml version="1.0" encoding="UTF-8"?>
<rrd>
    <version>0003</version>
    <step>5</step>
    <lastupdate>1290585118</lastupdate>
    <ds>
        <name>cpu1</name>
        <type>DERIVE</type>
        <minimal_heartbeat>300.0000</minimal_heartbeat>
        <min>0.0</min>
        <max>1.0000</max>
        <last_ds>69375.6708</last_ds>
        <value>0.0001</value>
        <unknown_sec>0</unknown_sec>
    </ds>
    <ds>
        <name>cpu0</name>
        <type>DERIVE</type>
        <minimal_heartbeat>300.0000</minimal_heartbeat>
        <min>0.0</min>
        <max>1.0000</max>
        <last_ds>69375.6708</last_ds>
        <value>0.0001</value>
        <unknown_sec>0</unknown_sec>
    </ds>
...

Solution

  • According to the FAQ,

    VTD-XML fully conforms with W3C XPath 1.0 recommendation. It supports all the built-in functions. It also supports many XPath 2.0 functions.

    So if VTD-XML is rejecting a valid XPath 1.0 expression, there would seem to be a bug in VTD-XML. But the problem could be in the XPath expression, or in your code that uses VTD-XML.

    The XPath expression you give appears to be valid. It's not very efficient though, so there may be a better way to do this in VTD-XML, without using XPath. E.g. going through the input records and counting till you get to the ds element whose name is cpu1.