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?

4

2 回答 2

4

使用 Chris Heald 的答案,我设法用 REXML 做到了这一点——不需要 Nokogiri。诀窍是使用 XPath.each 而不是 XPath.first。

这有效:

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"))
于 2013-06-13T10:03:35.627 回答
3

我不确定 rexml 是否这样做,但我通常建议尽可能不要使用 rexml。

Nokogiri 做得很好:

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>

结果输出:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <name>foobar</name>
</config>
于 2013-06-13T09:52:01.667 回答