我有一个基本XML,需要通过Ruby脚本来修改。XML如下所示:
<?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我想做的是用其他的东西来改变值("So和so")。对于这个用例,我似乎找不到任何例子(不管是在文档中还是其他方面)。甚至可以在Ruby1.9.3中完成吗?
发布于 2013-06-13 10:03:35
使用Chris的答案,我成功地使用了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-13 09:52:01
我不确定rexml是否能做到这一点,但我通常建议您不要使用rexml (如果可能的话)。
诺科吉里做得很好:
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>https://stackoverflow.com/questions/17083973
复制相似问题