3

次の要素の属性を取得して、前の要素で次のように使用することは可能ですか?:

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

の中へ:

<title id="ID1">1. Section X</title>
<paragraph number="1">Stuff</paragraph>
<title id="ID2">2. Section Y</title>
<paragraph number="2">Stuff</paragraph>

私はこのようなものを持っていますが、ノードセットまたは文字列のエラーが発生します:

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

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

1 に答える 1

1

next_sibling仕事をする必要があります

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>

空白もノードであるため、next_sibling2回呼び出す必要があります。多分これを回避する方法があります。

または、xpath式を使用して、次の段落の数値属性を選択することもできます。

t['id'] = "ID#{t.xpath('following-sibling::paragraph/@number').first}"
于 2009-12-06T11:10:54.877 に答える