是否有一个DRYer XPath表达式用于联合?

时间:2011-04-01 17:02:21

标签: xpath union expression dry

这非常适合查找类似按钮的HTML元素,(故意简化):

  //button[text()='Buy']
| //input[@type='submit' and @value='Buy']
| //a/img[@title='Buy']

现在我需要将此约束到上下文。例如,出现在标记框内的“购买”按钮:

//legend[text()='Flubber']

这样可行,(..让我们进入包含的字段集):

  //legend[text()='Flubber']/..//button[text()='Buy']
| //legend[text()='Flubber']/..//input[@type='submit' and @value='Buy']
| //legend[text()='Flubber']/..//a/img[@title='Buy']

但有没有办法简化这个?可悲的是,这种事情不起作用:

//legend[text()='Flubber']/..//(
  button[text()='Buy']
| input[@type='submit' and @value='Buy']
| a/img[@title='Buy'])

(请注意,这是针对浏览器中的XPath,因此XSLT解决方案无济于事。)

2 个答案:

答案 0 :(得分:3)

在单个谓词中组合多个条件:

//legend[text()='Flubber']/..//*[self::button[text()='Buy'] or 
                                 self::input[@type='submit' and @value='Buy'] or
                                 self::img[@title='Buy'][parent::a]]

英文:

  

选择父级的所有后代(或父级本身)   对于任何legend元素   文本“Flubber”是1)button中的任何一个   具有文本“购买”或2)的元素   input元素具有属性   type,其值为“提交”和   名为value的属性,其值为   “买”或3)img有一个   名为title的属性,带有值   “买”的父母是a   元件。

答案 1 :(得分:2)

来自评论:

  

稍微调整以获得A   而不是IMG:   self::a[img[@title='Buy']]。 (现在如果   只有'买'可以减少

使用此XPath 1.0表达式:

//legend[text() = 'Flubber']/..
   //*[
      self::button/text()
    | self::input[@type = 'submit']/@value
    | self::a/img/@title
    = 'Buy'
   ]

编辑:我没有看到父访问者。仅在一个方向的其他方式:

//*[legend[text() = 'Flubber']]
   //*[
      self::button/text()
    | self::input[@type = 'submit']/@value
    | self::a/img/@title
    = 'Buy'
   ]