nokogiri 可以处理带有可选标签的 css 选择器吗?

Can nokogiri handle css selector with optional tags?

是否可以在 nokogiri 中使用两个可选标签定义 css 选择器?

作为(不工作的)示例:

  document.css('/hello-world [greeting|gruss]').each{|g| 
    ...
  }

我想以正确的顺序获取所有 'greeting' 和 'gruss' 标签。

在一个完整的最小无效示例中:

XML = <<-XML
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="hello.xsl"?>
<hello-world>   
  <greeting>Hello, World!</greeting>
  <gruss>Hallo, Welt!</gruss>
</hello-world>
XML

require 'nokogiri'

document = Nokogiri::XML(XML)
[
#This two are working, but it is in two different loops:
  '/hello-world greeting',
  '/hello-world gruss',
#This does not work:
  '/hello-world [greeting|gruss]',  #Does not work
].each{|css_path|
  puts "Scan css path '%s':" % css_path
  document.css(css_path).each{|g| puts "  Found: %s" % g.content }
}

结果是:

Scan css path '/hello-world greeting':
  Found: Hello, World!
Scan css path '/hello-world gruss':
  Found: Hallo, Welt!
Scan css path '/hello-world [greeting|gruss]':

最后 css 个元素以 Nokogiri::XML::XPath::SyntaxError 结尾。是否有可能使用一个 css-选择器获取两个标签中的所有元素?

在 CSS 中,您只需使用逗号来 select 多个节点:

document.css 'greeting, gruss'

如果您想更具体,您需要重复整个 select 或:

document.css 'hello-world greeting, hello-world gruss'

目前没有办法缩短它(类似 any psuedo-class 的东西可以工作,但在 Nokogiri 中不可用)。

在 XPath 中你可以做类似的事情

document.xpath '//hello-world//*[name() = "greeting" or name() = "gruss"]'

这并没有缩短,但意味着您可以避免重复查询的第一部分。

如果这是您打算经常做的事情,您也许还可以考虑创建一个自定义函数,它可以从 CSS 或 XPath 中使用。