Mike Mike - 1 month ago 18
Ruby Question

How do I search and replace an attibute value in my Nokogiri doc?

I'm using Rails 4.2.7. How do I replace an attribute value in my Nokogiri doc? I have idnetified the attribute in quesiton using

doc.xpath("//pre[@class='text-results']").xpath("meta[@http-equiv='Content-Type']").attr("content").to_s


but when I try and assign a different value to it, nothing is getting returned in my rails conosle, whcih leads me to believe I'm not doing it right ...

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 >


Any help is appreciated,

Edit: Error in respone to answer given ...

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>'

Answer

Try the []= method

node["content"] = "text/html; charset=iso8849"

If you want to update the first one

doc.xpath("//pre[@class='text-results']").xpath("meta[@http-equiv='Content-Type']").first["content"] = "text/html; charset=iso8849"

Or every node

doc.xpath("//pre[@class='text-results']").xpath("meta[@http-equiv='Content-Type']").each { |node| node["content"] = "text/html; charset=iso8849" }