How can I get nokogiri to select node attributes and add them to other nodes?

Is it possible to capture the following attributes of an element and use them in the previous one?

<title>Section X</title>
<paragraph number="1">Stuff</paragraph>
<title>Section Y</title>
<paragraph number="2">Stuff</paragraph>

in

<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 I get nodal 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']"))}
+3
source share
1 answer

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}"
+1
source

Source: https://habr.com/ru/post/1724611/


All Articles