GPath to find if a table header contains a matching string

不羁岁月 提交于 2020-01-06 02:30:33

问题


I'm parsing an HTML file into a well-formed XML document using NekoHTML parser. However I can't quite figure out the GPath so that I can identify the table that has the "Settings" string.

def parser = new org.cyberneko.html.parsers.SAXParser()
parser.setFeature('http://xml.org/sax/features/namespaces', false)

    def html = 
    ''' 
        <html>
            <title>Hiya!</title>
        </html>
        <body>
            <table>
                <tr>
                    <th colspan='3'>Settings</th>
                    <td>First cell r1</td>
                    <td>Second cell r1</td>
                </tr>
            </table>
            <table>
                <tr>
                    <th colspan='3'>Other Settings</th>
                    <td>First cell r2</td>
                    <td>Second cell r2</td>
                </tr>
            </table>
    '''

    def slurper = new XmlSlurper(parser)
    def page = slurper.parseText(html)

In this sample, the first table should be selected so that I can iterate over other row values in it. Can someone help me with this GPath please?

EDIT: Side question - why does

println page.HTML.HEAD.TITLE

print an empty string, shouldn't it return the title?


回答1:


  1. To get the table with 'Settings' in the header, you should be able to do:

    def settingsTableNode = page.BODY.TABLE.find { table ->
      table.TBODY.TR.TH.text() == 'Settings'
    }
    
  2. page points to the root of the document, so you don't need the HTML. All you should need to do is:

    println page.HEAD.TITLE
    


来源:https://stackoverflow.com/questions/9260461/gpath-to-find-if-a-table-header-contains-a-matching-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!