是否有可能获取以下元素的属性并在前一个中使用它们?:
<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']"))}
答案 0 :(得分: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}"