rubyxpathrexml

Ruby/REXML: Change a tag value from XPath


I have a base XML that I need to modify through a Ruby script. The XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
    <config>
        <name>So and So</name>
    </config>

I am able to print the value of <name>:

require 'rexml/document'
include REXML

xmlfile = File.new("some.xml")
xmldoc = Document.new(xmlfile)

name = XPath.first(xmldoc, "/config/name")
p name.text # => So and so

What I would like to do is to change the value ("So and so") by something else. I can't seem to find any example (in the documentation or otherwise) for that use case. Is it even possible to do in Ruby 1.9.3?


Solution

  • Using Chris Heald answer I managed to do this with REXML - no Nokogiri necessary. The trick is to use XPath.each instead of XPath.first.

    This works:

    require 'rexml/document'
    include REXML
    
    xmlfile = File.new("some.xml")
    xmldoc = Document.new(xmlfile)
    
    XPath.each(xmldoc, "/config/name") do|node|
      p node.text # => So and so
      node.text = 'Something else'
      p node.text # => Something else
    end
    
    xmldoc.write(File.open("somexml", "w"))