如何替换Nokogiri文档中的属性值?我使用以下方法确定了相关属性:
doc.xpath("//pre[@class='text-results']").xpath("meta[@http-equiv='Content-Type']").attr("content").to_s
但是当我尝试为它分配一个不同的值时,我的Rails控制台中没有返回任何内容,这让我相信我做得不对:
2.3.0 :027 > doc.xpath("//pre[@class='text-results']").xpath("meta[@http-equiv='Content-Type']").attr("content") = "text/html; charset=iso8849";
2.3.0 :028 >
回答给出的答案时出错:
2.3.0 :005 > doc.xpath("//pre[@class='text-results']").xpath("meta[@http-equiv='Content-Type']")["content"] = "text/html; charset=iso8849"
NoMethodError: undefined method `[]=' for #<Nokogiri::XML::NodeSet:0x007f820271c628>
Did you mean? []
from (irb):5
from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/console.rb:110:in `start'
from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/console.rb:9:in `start'
from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/commands_tasks.rb:68:in `console'
from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
我正在使用Rails 4.2.7。
答案 0 :(得分:1)
尝试使用[]=
方法
node["content"] = "text/html; charset=iso8849"
如果您想更新第一个
doc.xpath("//pre[@class='text-results']").xpath("meta[@http-equiv='Content-Type']").first["content"] = "text/html; charset=iso8849"
或每个节点
doc.xpath("//pre[@class='text-results']").xpath("meta[@http-equiv='Content-Type']").each { |node| node["content"] = "text/html; charset=iso8849" }