Dynamic Node Names

168 views
Skip to first unread message

Spencer Rogers

unread,
Sep 20, 2010, 4:03:54 PM9/20/10
to nokogiri-talk
Hey all, I'm having trouble using dynamic node names when creating an
XML document in Nokogiri.

For a static node name I would do the following:

xml.myNodeName "This is my node text"

But what if I want to use a dynamic name for my node? I would assume
it would be similar to the example below but I haven't been able to
get it to work... Any ideas?

for item in myItems
xml[item.itemId] item.itemText
end # for each item


I appreciate any assistance you can give, thanks!

Spencer

Mike Dalessio

unread,
Sep 21, 2010, 8:28:00 AM9/21/10
to nokogi...@googlegroups.com
Hi,

On Mon, Sep 20, 2010 at 4:03 PM, Spencer Rogers <spence...@gmail.com> wrote:
Hey all, I'm having trouble using dynamic node names when creating an
XML document in Nokogiri.

For a static node name I would do the following:

xml.myNodeName "This is my node text"

But what if I want to use a dynamic name for my node?  I would assume
it would be similar to the example below but I haven't been able to
get it to work...  Any ideas?

for item in myItems
    xml[item.itemId] item.itemText
end # for each item


I assume you are using the Nokogiri::XML::Builder class? If so, then use Object#send to create your nodes:

node_names = ["foo", "bar", "bazz"]

builder = Nokogiri::XML::Builder.new do |xml|
  xml.root do
    node_names.each { |name| xml.send name, "some content" }
  end
end

puts builder.to_xml
# => <?xml version="1.0"?>
#    <root>
#      <foo>some content</foo>
#      <bar>some content</bar>
#      <bazz>some content</bazz>
#    </root>

If your node names may collide with Object methods (like "id" or "class") then you may want to append an underscore to the method name, which tells the Builder class explicitly that you're creating a node, and not invoking the Object method:

builder = Nokogiri::XML::Builder.new do |xml|
  xml.root do
    node_names.each { |name| xml.send "#{name}_", "some content" }
  end
end

 

I appreciate any assistance you can give, thanks!

Spencer

--
You received this message because you are subscribed to the Google Groups "nokogiri-talk" group.
To post to this group, send email to nokogi...@googlegroups.com.
To unsubscribe from this group, send email to nokogiri-tal...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/nokogiri-talk?hl=en.


Reply all
Reply to author
Forward
0 new messages