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

别说谁变了你拦得住时间么 提交于 2019-12-03 05:46:43

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