set tag attribute and add plain text content to the tag using nokogiri builder (ruby) set tag attribute and add plain text content to the tag using nokogiri builder (ruby) xml xml

set tag attribute and add plain text content to the tag using nokogiri builder (ruby)


There are two approaches you can use.

Using .text

You can call the .text method to set the text of a node:

builder = Nokogiri::XML::Builder.new { |xml|  xml.Transaction("requestName" => "OrderRequest") do    xml.Option("b" => "hive"){ xml.text("hello") }  end}

which produces:

<?xml version="1.0"?><Transaction requestName="OrderRequest">  <Option b="hive">hello</Option></Transaction>

Solution using text parameter

Alternatively, you can pass the text in as a parameter. The text should be passed in before the attribute values. In other words, the tag is added in the form:

tag "text", :attribute => 'value'

In this case, the desired builder would be:

builder = Nokogiri::XML::Builder.new { |xml|  xml.Transaction("requestName" => "OrderRequest") do    xml.Option("hello", "b" => "hive")  end}

Produces the same XML:

<?xml version="1.0"?><Transaction requestName="OrderRequest">  <Option b="hive">hello</Option></Transaction>