24

I'm trying to add an attribute to an existing Nokogiri node. What I've done is this:

node.attributes['foobar'] = Nokogiri::XML::Attr.new('foo', 'bar')

But I get the error:

TypeError Exception: wrong argument type String (expected Data)

What is a Data data type, and how do I add an attribute to the Nokogiri object?

Thanks!

Yuval Karmi
  • 26,277
  • 39
  • 124
  • 175

1 Answers1

56

I believe you should just need to use the []= method, i.e.

node['foo'] = 'bar'

You could also use node.set_attribute('foo', 'bar').

Greg Campbell
  • 15,182
  • 3
  • 44
  • 45
  • This is what the Nokogiri docs say to do. Are you sure your `node` object is actually a `Nokogiri::XML::Element`? What was the error you got when you did `node['foo'] = 'bar'`? – wuputah Sep 01 '10 at 03:24
  • actually, you're right - that was a mistake on my part. greg - do you mind hitting edit and submit on your question so i can upvote it? thanks! – Yuval Karmi Sep 01 '10 at 03:57
  • Done. I also linked to the RDoc for the method in question on Nokogiri::XML::Node. – Greg Campbell Sep 01 '10 at 16:41
  • another thing if you're wondering why this didn't work is to make sure that you're writing out the modified object. =) – wisbucky Apr 06 '16 at 18:42