【发布时间】:2014-08-05 14:03:00
【问题描述】:
我正在尝试更改以下 XML 文件中的数据。我确信数据将在<string> 标签中但在其中可以嵌套到任何程度的一件事。所以为了做到这一点,我想出了一个递归解决方案,它看起来像是正确的代码,但没有做任何改变。
C 或 C++ 中的递归很容易,因为更改很容易反映在实际参数中,但在 Ruby 中,我无法弄清楚如何反映这一点。
源 XML:
<document>
<string id="title">Continue without CableCARD?</string>
<string id="bodytext"/>
<string id = "f" >This is data1
<p>
<t>
this is data2
</t>
</p>
this is data3
</string>
</document>
Ruby 代码:
require 'nokogiri'
doc = Nokogiri::XML(File.open("d.xml"))
def rec_func(s)
if s.child.class == NilClass
return s
end
array = s.children()
array.each do |element|
if element == Nokogiri::XML::Text
s.content = s.content + "A"
else
element = rec_func(element)
puts "##########"
puts element
end
end
s.children = array # I added this statement as I was in doubt whether the changes in this array will be reflected in the parent s or not.
return s
end
doc.xpath("//string").each do |node|
k = rec_func node
puts "$$$$$$$$$$$$$$"
end
请有人建议对代码进行任何更改以使其正常工作。
【问题讨论】:
-
首先,条件
element == Nokogiri::XML::Text不起作用。element不等于它的类......你可能想这样做:Nokogiri::XML::Text === element。 -
它也不起作用