我有一个基本 XML,我需要通过 Ruby脚本进行修改. XML看起来像这样: ?xml version="1.0" encoding="UTF-8"? config nameSo and So/name /config 我可以打印 name的值: require 'rexml/document'include REXMLxmlfile = File
<?xml version="1.0" encoding="UTF-8"?>
<config>
<name>So and So</name>
</config>
我可以打印< 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
我想做的是用其他东西来改变价值(“一如既往”).我似乎无法找到该用例的任何示例(在文档中或其他方面).甚至可以在Ruby 1.9.3中做到吗?
使用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"))
