2009-12-03 2 views
3

는 다음과 같은 요소의 속성을 잡고이 같은 이전 하나에서 사용 할 수 있는가에nokogiri에서 노드 속성을 선택하여 다른 노드에 추가하려면 어떻게해야합니까?

<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']"))} 

답변

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_sibling을 두 번 호출해야합니다. 어쩌면 이것을 피할 수있는 방법이 있습니다. 잘 트릭 않습니다 -

은 또는 당신

t['id'] = "ID#{t.xpath('following-sibling::paragraph/@number').first}" 
+0

매우 아드리안 감사합니다 다음 단락의 수 속성을 선택 XPath 식을 사용할 수 있습니다 – ritchielee

관련 문제