【问题标题】:Ruby/REXML: Change a tag value from XPathRuby/REXML:从 XPath 更改标记值
【发布时间】:2013-06-13 09:45:36
【问题描述】:

我有一个需要通过 Ruby 脚本修改的基本 XML。 XML 如下所示:

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

我可以打印&lt;name&gt;的值:

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 中进行吗?

【问题讨论】:

    标签: ruby xpath rexml


    【解决方案1】:

    使用 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"))
    

    【讨论】:

      【解决方案2】:

      我不确定 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多