使用 nokogiri builder (ruby) 设置标签属性并将纯文本内容添加到标签中 [英] set tag attribute and add plain text content to the tag using nokogiri builder (ruby)

查看:31
本文介绍了使用 nokogiri builder (ruby) 设置标签属性并将纯文本内容添加到标签中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Nokogiri 构建 XML,其中一些标签在标签中同时具有属性和纯文本.所以我试图做到这一点:

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>

使用构建器我有这个:

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

呈现为:

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

所以它产生<Option b="hive" class="text">hello</Option>我想要的地方<Option b="hive">hello</Option>

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

我不知道该怎么做.如果我尝试通过向 Nokogiri 对象提供我想要的 XML 来获取它,它会准确地呈现我需要的内容,并将内部文本设置为 <Option> 标记设置为 children=[#<Nokogiri::XML::Text:0x80b9e3dc "hello">] 我不知道如何从构建器中设置它.

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.

如果有人在 Nokogiri 文档中提及此内容,我将不胜感激.

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

推荐答案

您可以使用两种方法.

使用 .text

可以调用.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
}

产生:

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

使用文本参数的解决方案

或者,您可以将文本作为参数传入.文本应该在属性值之前传入.换句话说,标签是以如下形式添加的:

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
}

生成相同的 XML:

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

这篇关于使用 nokogiri builder (ruby) 设置标签属性并将纯文本内容添加到标签中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆