Getting the siblings of a node with Nokogiri

六月ゝ 毕业季﹏ 提交于 2019-11-30 19:59:25
require 'nokogiri'
doc = Nokogiri::XML.parse(File.open('info.xml'))
details = doc.css('details').find{|node| node.css('id').text == "5678"}
email = details.css('email').text # => "zzzz@zzz.com"
images = details.css('image').map(&:text) # => ["images/4.jpg", "images/5.jpg"]

Update: There are shorter, arguably better, ways to grab the details node you want:

details = doc.at('details:has(id[text()="5678"])')

or

details = doc.search('id[text()="5678"] ~ *')

Those are both courtesy of pguardiario.

You can use ~, which is the css general sibling selector:

doc.search('id[text()="5678"] ~ *').map &:text
#=> ["zzzz@zzz.com", "images/4.jpg", "images/5.jpg"]

It's a little bit weird to use css with xml but it's so much easier to look at (than xpath).

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