2009-12-03 26 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两次。也许有一种方法可以避免这种情况。

或者您可以使用XPath表达式来选择下一段

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

非常感谢阿德里安的人数属性 - 这很好做的伎俩 – ritchielee 2009-12-06 22:43:55

相关问题