Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby nokogiri可以处理带有可选标记的css选择器吗?_Ruby_Xml Parsing_Nokogiri - Fatal编程技术网

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

Ruby nokogiri可以处理带有可选标记的css选择器吗?,ruby,xml-parsing,nokogiri,Ruby,Xml Parsing,Nokogiri,可以在nokogiri中使用两个可选标记定义css选择器吗 作为一个(不工作)示例: 我想把所有的“问候语”和“咕噜”标签按正确的顺序排列 在一个完整的最小不工作示例中: document.css('/hello-world [greeting|gruss]').each{|g| ... } XML = <<-XML <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="hell

可以在nokogiri中使用两个可选标记定义css选择器吗

作为一个(不工作)示例:

我想把所有的“问候语”和“咕噜”标签按正确的顺序排列

在一个完整的最小不工作示例中:

  document.css('/hello-world [greeting|gruss]').each{|g| 
    ...
  }
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 }
}

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

在css中,您只需使用逗号来选择多个节点:

document.css 'greeting, gruss'
如果要更具体,需要重复整个选择器:

document.css 'hello-world greeting, hello-world gruss'
目前还没有办法缩短这个时间(类似的东西可以工作,但在Nokogiri中不可用)

在XPath中,您可以执行以下操作

document.xpath '//hello-world//*[name() = "greeting" or name() = "gruss"]'
这并不更短,但意味着您可以避免重复查询的第一部分


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

我发现的一个解决方案是:使用
'./hello world//greeting |/hello world//gruss'
作为XPath。。但是我在寻找一个使用css的解决方案。
document.xpath '//hello-world//*[name() = "greeting" or name() = "gruss"]'