3

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?

Astaar
  • 5,858
  • 8
  • 40
  • 57

2 Answers2

4

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"))
Astaar
  • 5,858
  • 8
  • 40
  • 57
3

I'm not sure if rexml does this, but I generally recommend against using rexml if at all possible anyhow.

Nokogiri does this just fine:

require 'nokogiri'

xmldoc = Nokogiri::XML(DATA)
xmldoc.search("/config/name").each do |node|
  node.content = "foobar"
end

puts xmldoc.to_xml

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

And the resultant output:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <name>foobar</name>
</config>
Chris Heald
  • 61,439
  • 10
  • 123
  • 137