Reputation: 105053
This is what I'm trying to do:
xml = Nokogiri::XML::Builder.new do |x|
x.root do
x.book do
x.attribute('isbn', 12345) # Doesn't work!
x.text("Don Quixot")
end
end
end.doc
I know that I can do x.book(isbn: 12345)
, but this is not what I want. I want to add an attribute within the do/end
block. Is it at all possible?
The XML expected:
<root>
<book isbn="12345">Don Quixot</book>
</root>
Upvotes: 3
Views: 2278
Reputation: 1492
Add the attributes to the node like this
xml = Nokogiri::XML::Builder.new do |x|
x.root do
x.book(isbn: 1235) do
x.text('Don Quixot')
end
end
end.doc
Or, after re-rereading your question perhaps you wanted to add it to the parent further in the do block. In that case, this works:
xml = Nokogiri::XML::Builder.new do |x|
x.root do
x.book do
x.parent.set_attribute('isbn', 12345)
x.text('Don Quixot')
end
end
end.doc
Generates:
<?xml version="1.0"?>
<root>
<book isbn="1235">Don Quixot</book>
</root>
Upvotes: 6