How to convert Xpath to CSS

19,476

Solution 1

While an expression like (//E)[2] can't be represented with a CSS selector, an expression like E[2] can be emulated using the :nth-of-type() pseudo-class:

html > body > div > table > tbody > tr:nth-of-type(2) > td:nth-of-type(4)

Solution 2

Works good for me.

//Author: Oleksandr Knyga
function xPathToCss(xpath) {
    return xpath
        .replace(/\[(\d+?)\]/g, function(s,m1){ return '['+(m1-1)+']'; })
        .replace(/\/{2}/g, '')
        .replace(/\/+/g, ' > ')
        .replace(/@/g, '')
        .replace(/\[(\d+)\]/g, ':eq($1)')
        .replace(/^\s+/, '');
}
Share:
19,476
Kamil
Author by

Kamil

Updated on June 04, 2022

Comments

  • Kamil
    Kamil about 2 years

    My xpath is: /html/body/div/table/tbody/tr[2]/td[4]

    I need to get an CSS to use it in jsoup selector.

    I found a comparison between xpath and css: here, and it's said in their example (Second <E> element anywhere on page) that I can't do it. Xpath xpath=(//E)[2] CSS N\A.

    Maybe I can't find what I'm looking for. Any ideas?

    Here's the html I'm trying to parse (I need to get values: 1 and 3):

    <div class=tablecont>
        <table width=100%>
            <tr>
                <td class=header align=center>Panel Color</td>
                <td class=header align=center>Locked</td>
                <td class=header align=center>Unqualified</td>
                <td class=header align=center>Qualified</td>
                <td class=header align=center>Finished</td>
                <td class=header align=center>TOTAL</td>
            </tr>
            <tr>
                <td align=center>
                    <div class=packagecode>ONE</div>
                    <div>
                    <div class=packagecolor style=background-color:#FC0;></div>
                    </div>
                </td>
                <td align=center>0</td>
                <td align=center>0</td>
                <td align=center>1</td>
                <td align=center>12</td>
                <td align=center class=rowhead>53</td>
            </tr>
            <tr>
                <td align=center>
                    <div class=packagecode>two</div>
                    <div>
                        <div class=packagecolor style=background-color:#C3F;></div>
                    </div>
                </td>
                <td align=center>0</td>
                <td align=center>0</td>
                <td align=center>3</td>
                <td align=center>42</td>
                <td align=center class=rowhead>26</td>
            </tr>
        </table>
    </div>