Come posso ottenere nokogiri per selezionare gli attributi dei nodi e aggiungerli ad altri nodi?

StackOverflow https://stackoverflow.com/questions/1839565

  •  12-09-2019
  •  | 
  •  

Domanda

E 'possibile afferrare gli attributi di un successivo elemento e utilizzarli nella precedente in questo modo:?

<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>

Ho qualcosa come questo, ma ottenere gli errori serie di nodi o stringa:

frag = Nokogiri::XML(File.open("test.xml"))

frag.css('title').each { |text| 
text.set_attribute('id', "ID" + frag.css("title > paragraph['number']"))}
È stato utile?

Soluzione

next_sibling dovrebbe fare il lavoro

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>

A causa spazi bianchi è anche un nodo, si deve chiamare next_sibling due volte. Forse c'è un modo per evitare questo.

In alternativa è possibile utilizzare un'espressione XPath per selezionare l'attributo numero del paragrafo successivo

t['id'] = "ID#{t.xpath('following-sibling::paragraph/@number').first}"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top