Insert Text After Specific XML Tag in Nokogiri

寵の児 提交于 2019-12-25 05:15:07

问题


I'd like to create the following XML:

<?xml version="1.0">
<foo>
  <bar/>
  TEXT GOES HERE
</foo>

The structure is pretty simple to build with Nokogiri:

builder = Nokogiri::XML::Builder.new do |xml|
  xml.foo { 
    xml.bar {}
  }
end
puts builder.to_xml

What I can't figure out is how to insert the TEXT GOES HERE string inside <foo> but after <bar/>.

Obviously, xml.foo("TEXT GOES HERE") produces the text before <bar>. What am I missing?


回答1:


You want the text method:

require 'nokogiri'
builder = Nokogiri::XML::Builder.new do |xml|
  xml.foo { 
    xml.bar
    xml.text "TEXT GOES HERE"
  }
end

puts builder.doc
#=> <?xml version="1.0"?>
#=> <foo><bar/>TEXT GOES HERE</foo>


来源:https://stackoverflow.com/questions/10147762/insert-text-after-specific-xml-tag-in-nokogiri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!