3

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>
2
  • Can you manually whip up some XML to give us a visual of what you are trying to create? Commented Aug 30, 2017 at 17:07
  • @ddubs just updated the answer, see above Commented Aug 30, 2017 at 17:09

1 Answer 1

7

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.