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

寵の児 提交于 2019-12-03 11:42:56

问题


I am trying to build XML using Nokogiri with some tags that have both attributes and plain text inside the tag. So I am trying to get to this:

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

Using builder I have this:

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

which renders to:

<Transaction requestName="OrderRequest">
  <Option b="hive" class="text">hello</Option>
</Transaction>

So it produces <Option b="hive" class="text">hello</Option> where I would just like it to be <Option b="hive">hello</Option>

I am not sure how to do that. If I try to get a Nokogiri object by just feeding it the XML I want, it renders back exactly what I need with the internal text being within the <Option> tag set to children=[#<Nokogiri::XML::Text:0x80b9e3dc "hello">] and I don't know how to set that from builder.

If anyone has a reference to that in the Nokogiri documentation, I would appreciate it.


回答1:


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>


来源:https://stackoverflow.com/questions/16219343/set-tag-attribute-and-add-plain-text-content-to-the-tag-using-nokogiri-builder

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