How can I get nokogiri to select node attributes and add them to other nodes?
Question
Is it possible to grab a following element's attributes and use them in the preceding one like this?:
<title>Section X</title>
<paragraph number="1">Stuff</paragraph>
<title>Section Y</title>
<paragraph number="2">Stuff</paragraph>
into:
<title id="ID1">1. Section X</title>
<paragraph number="1">Stuff</paragraph>
<title id="ID2">2. Section Y</title>
<paragraph number="2">Stuff</paragraph>
I have something like this but get nodeset or string errors:
frag = Nokogiri::XML(File.open("test.xml"))
frag.css('title').each { |text|
text.set_attribute('id', "ID" + frag.css("title > paragraph['number']"))}
Solution
next_sibling
should do the job
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>
Because whitespace is also a node, you have to call next_sibling
twice. Maybe there is a way to avoid this.
Alternatively you can use an xpath expression to select the number attribute of the next paragraph
t['id'] = "ID#{t.xpath('following-sibling::paragraph/@number').first}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow