1

我有一个 xml 文件,我正在尝试通过 rake 任务对其进行更新。以下是 xml 和 rake 文件:

测试.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

运行这个脚本后,我期待这个 xml:

<root>
 <parent name='foo'>
  <child value='child of foo'/>
 </parent>
 <parent name='bar'>
  <child value='child of bar'/>
 </parent>
</root>

但相反,我得到了这个:

<root>
 <parent name='foo'>
  <child value='child of bar'/>
 </parent>
 <parent name='bar'>
  <child value=''/>
 </parent>
</root>

有什么理由吗?任何帮助都感激不尽。


更新:我可以通过替换元素迭代代码来更新属性值

 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"
 }

与以下

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"

但我仍然不知道为什么迭代代码不起作用。

4

0 回答 0