next_sibling must do the work
require 'rubygems'
require 'nokogiri'
frag = Nokogiri::XML(DATA)
frag.css('title').each { |t| t['id'] = "ID#{t.next_sibling.next_sibling['number']}" }
puts frag.to_xml
__END__
<root>
<title>Section X</title>
<paragraph number="1">Stuff</paragraph>
<title>Section Y</title>
<paragraph number="2">Stuff</paragraph>
</root>
Since space is also a node, you must call twice next_sibling. Perhaps there is a way to avoid this.
Alternatively, you can use the xpath expression to select the number attribute of the next paragraph
t['id'] = "ID#{t.xpath('following-sibling::paragraph/@number').first}"
source
share