Mike Mike - 4 months ago 35
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


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- `start'
from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties- `start'
from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties- `console'
from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties- `run_command!'
from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties- `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'


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" }