I've an xml file which I'm trying to update through a rake task. Following are the xml and rake files:
test.xml
<root>
<parent name='foo'>
<child value=''/>
</parent>
<parent name='bar'>
<child value=''/>
</parent>
</root>
rakefile.rb
require 'rexml/document'
task :configure do
xmlFilePath = "test.xml"
xmlFile = File.new(xmlFilePath)
xmlDoc = REXML::Document.new xmlFile
xmlDoc.root.elements.each("//parent[contains(@name, 'foo')]"){
|e| e.elements["//child"].attributes["value"] = "child of foo"
}
xmlDoc.root.elements.each("//parent[contains(@name, 'bar')]"){
|e| e.elements["//child"].attributes["value"] = "child of bar"
}
xmlFile.close()
newXmlFile = File.new(xmlFilePath, "w")
xmlDoc.write(newXmlFile)
newXmlFile.close()
end
After running this script, I was expecting this xml:
<root>
<parent name='foo'>
<child value='child of foo'/>
</parent>
<parent name='bar'>
<child value='child of bar'/>
</parent>
</root>
but instead I get this:
<root>
<parent name='foo'>
<child value='child of bar'/>
</parent>
<parent name='bar'>
<child value=''/>
</parent>
</root>
Any reasons why? Any help will be much appreciated.
Update: I'm able to update the attribute values by replacing the element iteration code
xmlDoc.root.elements.each("//parent[contains(@name, 'foo')]"){
|e| e.elements["//child"].attributes["value"] = "child of foo"
}
xmlDoc.root.elements.each("//parent[contains(@name, 'bar')]"){
|e| e.elements["//child"].attributes["value"] = "child of bar"
}
with the following
xmlDoc.root.elements["//parent[contains(@name, 'foo')]/child"].attributes["value"] = "child of foo"
xmlDoc.root.elements["//parent[contains(@name, 'bar')]/child"].attributes["value"] = "child of bar"
but I still don't know why the iteration code doesn't work.