Selecting a specific table using XPath

I have an XHTML document and I want to select only the table with class = "index" in it.

If I understand correctly, the descendant axis will select all nodes that will directly and indirectly descend from the current node, so this is what I have.

//descendant::table[@class="index"]

      

It doesn't seem to work when tested with xmlstarlet. Is my tool broken, or is the XPath expression incorrect?

+3


a source to share


4 answers


Based on your example page (metacritic.com/film/highscores.shtml), I would say you need to use:

//TABLE[@CLASS="index"] 
(or /descendant::TABLE[@CLASS="index"])

      

This is because the TABLE index with CLASS is written in upper case on the example page (XML and XPath are case sensitive).

This will work if you are targeting a specific page, but will probably be a problem if different pages use different cases for the same html tags.



Then you need an abomination like

//TABLE[@CLASS="index" or @class="index" or @Class="index" or ...]
|//table[@CLASS="index" or @class="index" or ...]
|...

      

As such, you may have to use Tidy before fetching information, or switch to a tool that specializes in HTML cleaning (instead of XPath).

+3


a source


I think //table[@class="index"]

this is what you want



+4


a source


Yes, the axis descendant

selects all nodes descending from the node context. But the key here is the context node.

For example, descendant::span

will fetch all span

descendants of the current node. In the same vein, it descendant::*

will fetch all descendant elements of the current node.

If you need to fit the table as well as children, the XPath you provided works great during my test:

//descendant::table[@class="index"]

      

... selects the table itself and the child codes.

If you only need to match the children of the table, first select the desired node and then match it to the descendants:

//table[@class="index"]/descendant::*

      

.. Selects only child table nodes.

+1


a source


use this code

   let $info :=($p//descendant::TABLE[@class="index"])
        return $info

      

0


a source







All Articles