1

rake タスクを使用して更新しようとしている xml ファイルがあります。以下は、xml ファイルと rake ファイルです。

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

このスクリプトを実行した後、次の 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