This Ruby code updates an xml file using a method which can be applied where ever a simple struct form is used. ie. <records><record id="1"><name/><description/></record><record id="2"><name/><description/></record>
#test.xml = "<pears><pear id="1254"/><name/><region/></pear><pear id="5656"><name/><region/></pear></pears>"
require 'rexml/document'
include REXML
class Update
def initialize
end
def update_item(doc_p, pelement_name)
#get the target xml file
file = File.new('test.xml')
doc = Document.new(file)
puts doc
# get a reference to the record
id = doc_p.root.elements["parameter[@id]"].attributes.get_attribute('id')
puts id
node = doc.root.elements[pelement_name + "[@id='#{id}']"]
puts node
rnode = map_record(node, doc_p)
puts doc
end
def map_record(o_node, doc_input)
# set the element values for each field
doc_input.elements.each('parameters/parameter') do |in_node|
field = in_node.attributes.get_attribute('field').to_s
in_node.elements.each('attributes/attribute') do | attributex|
attribute_name = attributex.attributes.get_attribute('name').to_s
attribute_value = attributex.attributes.get_attribute('value').to_s
o_field = o_node.elements[attribute_name]
o_field.add_attribute(attribute_name, attribute_value)
end
map(o_node, field, in_node.attributes.get_attribute('value').to_s)
end
o_node
end
def map(o_node, field, value)
o_element = o_node.elements[field]
o_element.text = value
o_element
end
end
if __FILE__ == $0
u = Update.new
doc = Document.new
parameters = Element.new('parameters')
parameter = Element.new('parameter')
parameter.add_attribute('id', '5656')
parameters.add_element(parameter)
parameter = Element.new('parameter')
parameter.add_attribute('field', 'name')
parameter.add_attribute('value', 'Harovin Gaia')
parameters.add_element(parameter)
parameter = Element.new('parameter')
parameter.add_attribute('field', 'region')
parameter.add_attribute('value', 'Niagara')
parameters.add_element(parameter)
doc.add_element(parameters)
u.update_item(doc, 'pear')
puts doc
end